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

  1. C supports two types of files:
  2. Text Files
  3. Store data as readable text
  4. Examples: .txt, .csv
  5. Data can be read/written using fprintf, fscanf, fgets, fputs
  6. Binary Files
  7. Store data in binary format (not human-readable)
  8. Examples: .bin, .dat
  9. Data can be read/written using fread and fwrite

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 existRead data from a text file
"w"Open for writing. Creates new file or overwrites existingWrite data to a text file
"a"Open for appending. Adds data at the endAdd new entries without deleting old data
"rb"Open for reading in binary modeRead binary file
"wb"Open for writing in binary modeWrite binary data
"ab"Open for appending in binary modeAppend binary data
"r+"Open for reading and writingModify existing text file
"w+"Open for reading and writing, overwritesCreate or overwrite text file
"a+"Open for reading and writing, appendRead and add data to text file

3. Example: Opening a Text File in Different Modes


#include <stdio.h>

int main() {
FILE *fp;

// Open file for writing
fp = fopen("example.txt", "w");
if(fp == NULL) {
printf("Error opening file.\n");
return 1;
}

fprintf(fp, "Hello World!\n"); // write to file
fclose(fp); // close file

// Open file for reading
fp = fopen("example.txt", "r");
if(fp == NULL) {
printf("Error opening file.\n");
return 1;
}

char str[50];
fgets(str, sizeof(str), fp); // read a line
printf("Read from file: %s", str);

fclose(fp);
return 0;
}

Sample Output:


Read from file: Hello World!

4. Key Points to Remember

  1. Text files store human-readable data, binary files store machine-readable data
  2. File modes determine how you can access and modify files
  3. Always check if file opened successfully (fp != NULL)
  4. Use fclose() to close files and free resources
  5. Useful for storing data permanently, like student records, employee databases, and logs