File handling allows programs to store and retrieve data permanently on storage devices, making data persistent even after program termination.
1. Types of File
- Text File – Stores data in readable characters.
- Binary File – Stores data in binary form; efficient for large data.
2. Opening & Closing Data File
- Opening a file: Use fopen() with mode (r, w, a, rb, wb, etc.)
FILE *fp;
fp = fopen(“data.txt”, “r”); // Open for reading
- Closing a file: Use fclose()
fclose(fp);
3. Read & Write Functions
- Text files:
- fprintf(fp, …) → Write formatted text
- fscanf(fp, …) → Read formatted text
- fprintf(fp, …) → Write formatted text
- Binary files:
- fwrite(ptr, size, n, fp) → Write binary data
- fread(ptr, size, n, fp) → Read binary data
- fwrite(ptr, size, n, fp) → Write binary data
4. Writing & Reading Data To/From Data File
FILE *fp = fopen(“data.txt”, “w”);
fprintf(fp, “Name: Alice\nMarks: 85\n”);
fclose(fp);
fp = fopen(“data.txt”, “r”);
char name[20];
int marks;
fscanf(fp, “Name: %s\nMarks: %d”, name, &marks);
fclose(fp);
5. Updating Data File
- Read existing data, modify it, and write back to file.
- Use temporary file method or random access functions.
6. Random Accessing Files
- fseek() → Move file pointer to a specific location.
- ftell() → Returns current position of file pointer.
- rewind() → Move file pointer to beginning.
fseek(fp, 0, SEEK_SET); // Go to beginning
7. Printing a File
- Display contents of a file on screen using loops:
char ch;
FILE *fp = fopen(“data.txt”, “r”);
while((ch = fgetc(fp)) != EOF) {
putchar(ch);
}
fclose(fp);
Key Takeaways
- File handling provides permanent storage for program data.
- Types: Text (readable) and Binary (efficient).
- Open files with fopen(), close with fclose().
- Read/write using fscanf/fprintf (text) or fread/fwrite (binary).
- Random access (fseek, ftell) allows direct modification.
- Updating a file often requires reading, modifying, and writing back.
- Loop through file contents to print or process data.