Nearby lessons

66 of 72

C - File Modes

File modes tell C how a file should be opened. The most common beginner modes are r for reading, w for writing, and a for appending.

1. Common File Modes

ModePurposeIf the file does not existIf the file exists
rReadOpening failsReads existing content
wWriteCreates the fileErases old content
aAppendCreates the fileKeeps old content and adds at the end

Important: Use w only when you want to replace the existing file contents.

2. Example of Write and Append Modes

This example writes one line, then appends another line without removing the first one.

Example02
CCode Cell
1#include <stdio.h>
2 
3int main(void) {
4 FILE *fp = fopen("modes.txt", "w");
5 if (fp == NULL) {
6 printf("Could not open file\n");
7 return 1;
8 }
9 fprintf(fp, "First line\n");
10 fclose(fp);
11 
12 fp = fopen("modes.txt", "a");
13 if (fp == NULL) {
14 printf("Could not open file\n");
15 return 1;
16 }
17 fprintf(fp, "Second line\n");
18 fclose(fp);
19 
20 printf("File updated successfully\n");
21 return 0;
22}
Output
File updated successfully
📝 Key Takeaways
  • The r mode opens an existing file for reading.
  • The w mode creates a file or erases its existing contents.
  • The a mode creates a missing file or adds data at the end.
  • Always check whether fopen returns NULL.

🧠 Test Your Knowledge

3 Questions
Progress: 0 / 3