C Programming File Handling: File Types and Modes Explained
Learn file handling in C with a complete guide to file types and modes. Understand how to read, write, and append files using different file access modes in C programming.
1. File Types in C
C supports two main types of files:
- Text Files
- Contain human-readable characters
- Each line ends with a newline character (
\n) - Example:
.txt,.c,.csv - Binary Files
- Contain non-readable data (raw bytes)
- Used to store images, audio, or compiled programs
- Example:
.dat,.bin,.exe
Key Difference:
| Text FileBinary File | |
| Human-readable | Not human-readable |
| Handles data line by line | Handles data byte by byte |
Uses functions like fprintf, fscanf | Uses fwrite, fread |
2. File Modes in C
The file mode defines how a file is opened (read, write, append, etc.).
Common Modes:
| ModeMeaningUsage | ||
"r" | Open file for reading. File must exist. | fopen("file.txt", "r"); |
"w" | Open file for writing. Creates new file or truncates existing file. | fopen("file.txt", "w"); |
"a" | Open file for appending. Writes are added at end. | fopen("file.txt", "a"); |
"r+" | Open file for reading and writing. File must exist. | fopen("file.txt", "r+"); |
"w+" | Open file for reading and writing. Creates new file or truncates existing. | fopen("file.txt", "w+"); |
"a+" | Open file for reading and appending. Creates new file if not exists. | fopen("file.txt", "a+"); |
Binary Mode:
- Add
"b"to any mode for binary files - Example:
"rb","wb","ab"
3. Example: Using File Modes
Explanation:
"w"mode creates a new file or overwrites existing file"r"mode reads content from the filefclose()closes the file to save changes
4. Best Practices for File Handling
- Always check if file pointer is
NULLafterfopen() - Use
fclose()to close files properly - Use binary mode for non-text files
- Avoid hardcoding file paths; use relative paths if possible
- Use error handling for robust programs