File Types and File Modes in C Programming (Complete Guide with Examples)
This tutorial explains file handling in C, including different file types and file access modes. It covers how to open, read, write, and manipulate files efficiently for data storage and retrieval in real-world applications.
1. File Types in C
- C supports two types of files:
- Text Files
- Store data as readable text
- Examples:
.txt,.csv - Data can be read/written using
fprintf,fscanf,fgets,fputs - Binary Files
- Store data in binary format (not human-readable)
- Examples:
.bin,.dat - Data can be read/written using
freadandfwrite
2. File Access Modes in C
When opening a file with fopen(), the mode determines how the file will be used:
| ModeDescriptionUse Case | ||
"r" | Open for reading. File must exist | Read data from a text file |
"w" | Open for writing. Creates new file or overwrites existing | Write data to a text file |
"a" | Open for appending. Adds data at the end | Add new entries without deleting old data |
"rb" | Open for reading in binary mode | Read binary file |
"wb" | Open for writing in binary mode | Write binary data |
"ab" | Open for appending in binary mode | Append binary data |
"r+" | Open for reading and writing | Modify existing text file |
"w+" | Open for reading and writing, overwrites | Create or overwrite text file |
"a+" | Open for reading and writing, append | Read and add data to text file |
3. Example: Opening a Text File in Different Modes
Sample Output:
4. Key Points to Remember
- Text files store human-readable data, binary files store machine-readable data
- File modes determine how you can access and modify files
- Always check if file opened successfully (
fp != NULL) - Use
fclose()to close files and free resources - Useful for storing data permanently, like student records, employee databases, and logs