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:

  1. Text Files
  2. Contain human-readable characters
  3. Each line ends with a newline character (\n)
  4. Example: .txt, .c, .csv
  5. Binary Files
  6. Contain non-readable data (raw bytes)
  7. Used to store images, audio, or compiled programs
  8. Example: .dat, .bin, .exe

Key Difference:

Text FileBinary File
Human-readableNot human-readable
Handles data line by lineHandles data byte by byte
Uses functions like fprintf, fscanfUses 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:

  1. Add "b" to any mode for binary files
  2. Example: "rb", "wb", "ab"

3. Example: Using File Modes


#include <stdio.h>

int main() {
FILE *fp;

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

fprintf(fp, "Hello, TextNotes!\n");
fclose(fp);

// Open file in read mode
fp = fopen("example.txt", "r");
char str[100];
if(fp != NULL) {
while(fgets(str, 100, fp) != NULL)
printf("%s", str);
fclose(fp);
}

return 0;
}

Explanation:

  1. "w" mode creates a new file or overwrites existing file
  2. "r" mode reads content from the file
  3. fclose() closes the file to save changes

4. Best Practices for File Handling

  1. Always check if file pointer is NULL after fopen()
  2. Use fclose() to close files properly
  3. Use binary mode for non-text files
  4. Avoid hardcoding file paths; use relative paths if possible
  5. Use error handling for robust programs