PPS - File Handling Concepts
Q1. Explain any 3 directory methods with example.
1. mkdir() - Make Directory
Purpose: Creates a new directory.
Syntax: int mkdir(const char *pathname, mode_t mode);
Example:
#include <sys/stat.h>
int main() {
mkdir("NewFolder", 0777);
return 0;
2. opendir() and readdir() - Open and Read Directory
Purpose: Used to open a directory and read its contents.
Example:
#include <stdio.h>
#include <dirent.h>
int main() {
DIR *d;
struct dirent *dir;
d = opendir(".");
if (d) {
while ((dir = readdir(d)) != NULL) {
printf("%s\n", dir->d_name);
}
closedir(d);
return 0;
3. rmdir() - Remove Directory
Purpose: Deletes an empty directory.
Example:
#include <unistd.h>
int main() {
rmdir("NewFolder");
return 0;
Q2. Explain text and binary files with example.
Text Files:
- Stores data in human-readable ASCII format.
- Example:
#include <stdio.h>
int main() {
FILE *fptr;
fptr = fopen("data.txt", "w");
fprintf(fptr, "Hello, this is a text file.\n");
fclose(fptr);
char ch;
fptr = fopen("data.txt", "r");
while ((ch = fgetc(fptr)) != EOF) putchar(ch);
fclose(fptr);
return 0;
Binary Files:
- Stores data in machine-readable binary format.
- Example:
#include <stdio.h>
struct student { char name[20]; int age; };
int main() {
struct student s1 = {"Rahul", 20}, s2;
FILE *fptr = fopen("student.dat", "wb");
fwrite(&s1, sizeof(s1), 1, fptr);
fclose(fptr);
fptr = fopen("student.dat", "rb");
fread(&s2, sizeof(s2), 1, fptr);
fclose(fptr);
printf("Name: %s\nAge: %d\n", s2.name, s2.age);
return 0;
Difference Table:
Text File vs Binary File
- Human-readable vs Machine-readable
- Larger in size vs Compact
- Can be opened manually vs Cannot be opened manually
- Example: .txt vs .dat