File Handling in C - Easy Notes
1. Why File Handling?
- To store data permanently (unlike variables which store temporarily in RAM).
- Files allow saving and retrieving data even after program ends.
2. File Types in C
- Text files: store readable characters (e.g., .txt)
- Binary files: store data in binary format (e.g., .dat)
3. File Operations
1. Create/Open a file
2. Read from a file
3. Write to a file
4. Close the file
4. File Opening Modes with fopen()
FILE *fptr;
fptr = fopen("filename.txt", "mode");
Modes:
- "r" : Open for reading (file must exist)
- "w" : Open for writing (erases if file exists, creates if not)
- "a" : Append to file (creates if not exists)
- "r+" : Read + Write (file must exist)
- "w+" : Read + Write (erases if exists)
- "a+" : Read + Append (creates if not exists)
5. Writing to a File
fputc('A', fptr); // write single char
fputs("Hello", fptr); // write string
fprintf(fptr, "%d", 100); // formatted output
Page 1
File Handling in C - Easy Notes
6. Reading from a File
ch = fgetc(fptr); // read single char
fgets(str, size, fptr); // read string/line
fscanf(fptr, "%d", &num); // formatted input
7. Closing a File
fclose(fptr);
Always close the file to free up system resources.
8. Example: Write and Read from File
#include <stdio.h>
int main() {
FILE *file;
char ch;
// Open file for writing and reading
file = fopen("example.txt", "w+");
fputs("Hello!", file); // Write to file
rewind(file); // Go back to start
while ((ch = fgetc(file)) != EOF) {
putchar(ch); // Print each character
}
fclose(file);
return 0;
}
9. Checking if File Opened Successfully
Page 2
File Handling in C - Easy Notes
if (file == NULL) {
printf("File could not be opened.\n");
return 1;
}
10. File Handling Functions Summary
Function Purpose
fopen() Open file
fclose() Close file
fgetc() Read char
fputc() Write char
fgets() Read string/line
fputs() Write string
fscanf() Read formatted data
fprintf() Write formatted data
rewind() Go to beginning of file
fseek() Move file pointer
ftell() Get current position
Page 3