File Handling in C
Reading, Writing, and Managing Files
in C Programming
What is File Handling?
• File handling in C allows us to create, read, write, and
close files.
• It is useful for storing data permanently instead of using
variables.
Example file operations:
1. Opening a file
2. Reading and writing data
3. Closing a file
File Opening Modes
• `r` - Read mode (file must exist)
• `w` - Write mode (new file or overwrites)
• `a` - Append mode (adds to the existing
file)
• `r+` - Read and write mode
• `w+` - Read and write (overwrites file)
• `a+` - Read and write (appends data)
Writing to a File
• Use `fopen()` to open a file in write mode.
• Use `fprintf()` or `fputs()` to write data.
Example:
FILE *fp = fopen("example.txt", "w");
fprintf(fp, "Hello, World!\n");
fclose(fp);
Reading from a File
• Use `fopen()` to open a file in read mode.
• Use `fgets()` or `fscanf()` to read data.
char data[100];
FILE *fp = fopen("example.txt", "r");
fgets(data, 100, fp);
printf("%s", data);
fclose(fp);
Closing a File
• Always close a file to prevent data loss.
• Use `fclose(fp);` to close an open file.
Example:
FILE *fp = fopen("example.txt", "r");
fclose(fp);