C Files

1. What is File Handling in C?
C Files handling allows a program to store data permanently in a file on disk.
Types of files in C:
Text files → store readable characters (
.txt)Binary files → store data in binary format (
.bin)
File handling in C uses the
FILEstructure provided instdio.h.
2. Opening a File
filename→ name of the filemode→ how the file is to be opened
| Mode | Description |
|---|---|
"r" | Read (file must exist) |
"w" | Write (creates file or overwrites) |
"a" | Append (write at end, creates file) |
"r+" | Read & write (file must exist) |
"w+" | Read & write (creates/overwrites) |
"a+" | Read & append (creates file) |
3. Closing a File
Always close a file after operations to save data and free resources.
4. Reading from a File
fgetc()→ read a single characterfgets()→ read a line/stringfscanf()→ formatted input
Example: Reading a file character by character
5. Writing to a File
fputc()→ write a single characterfputs()→ write a stringfprintf()→ formatted output
Example: Writing to a file
6. Reading & Writing (r+) Example
7. Checking File Open
Always check if
fopenwas successful before performing operations.
8. Key Points About C File Handling
Use
FILE *for file operations.Always open a file with proper mode (
r,w,a, etc.).Always close files using
fclose()after operations.Use
fgetc(),fgets(),fputc(),fputs(),fprintf(),fscanf()for reading/writing.Use
fseek(),ftell(), andrewind()for file pointer control.File handling allows persistent storage beyond program execution.
