Nearby lessons

72 of 72

C - Append to a File

Appending means adding new information to the end of a file while keeping the existing content. Learn how to use the "a" mode with fopen().

1. Append Data Using a Mode

Open the file with "a" and write the new content. Existing data stays in the file.

Example01
CCode Cell
1#include <stdio.h>
2 
3int main(void) {
4 FILE *fp = fopen("log.txt", "a");
5 
6 if (fp == NULL) {
7 printf("Could not open the file\n");
8 return 1;
9 }
10 
11 fprintf(fp, "A new log entry was added.\n");
12 fclose(fp);
13 
14 printf("New entry appended\n");
15 return 0;
16}
Output
New entry appended

2. Difference Between w and a

ModeResult
wCreates a missing file or erases existing contents.
aCreates a missing file or adds new content at the end.
Example02
CCode Cell
1#include <stdio.h>
2 
3int main(void) {
4 FILE *fp = fopen("notes.txt", "w");
5 if (fp == NULL) return 1;
6 fprintf(fp, "First line\n");
7 fclose(fp);
8 
9 fp = fopen("notes.txt", "a");
10 if (fp == NULL) return 1;
11 fprintf(fp, "Second line\n");
12 fclose(fp);
13 
14 printf("Both lines are saved\n");
15 return 0;
16}
Output
Both lines are saved

3. Common Uses of Append Mode

Append mode is useful for log files, activity records, simple journals, and adding new entries to a text file without deleting earlier entries.

📝 Key Takeaways
  • The a mode adds new data at the end of a file.
  • Existing content is kept when using a mode.
  • If the file does not exist, a mode creates it.
  • The w mode replaces old content, while a mode preserves it.

🧠 Test Your Knowledge

3 Questions
Progress: 0 / 3