In this tutorial, you'll learn how to append text to an existing text file using the C programming language. Appending means adding new content to the end of a file without erasing what's already there — perfect for logs, journals, and any file that accumulates data over time. The entire trick is a single character in the fopen mode string: "a" instead of "w". Change "w" to "a" and everything else stays the same.
📝 Problem Statement
Write a program in C to append text to an existing text file.
⚙️ How the Program Works
The program follows a simple open-write-close sequence:
- Ask for the filename (or hard-code it) and the text to append.
- Open the file in append mode:
fopen("filename.txt", "a"). - Check for
NULLin case the file cannot be opened or created. - Write the new text with
fputs()orfprintf(). - Close the file with
fclose()to flush buffers and release the handle.
💻 Complete C Program
#include <stdio.h>
int main(void)
{
FILE *fp;
char filename[100];
char text[1024];
printf("Enter the filename to append to: ");
scanf("%99s", filename);
/* Clear the leftover newline from the previous scanf */
while (getchar() != '\n' && !feof(stdin))
;
printf("Enter the text to append: ");
fgets(text, sizeof(text), stdin);
/* Open the file in append mode.
"a" preserves existing content and writes at the end.
Creates the file if it does not exist. */
fp = fopen(filename, "a");
if (fp == NULL)
{
printf("Error: Could not open '%s' for appending.\n", filename);
return 1;
}
/* Write the new text to the end of the file */
fputs(text, fp);
fclose(fp);
printf("Text appended to '%s' successfully.\n", filename);
return 0;
}🖥️ Sample Output
Assume notes.txt already contains three lines from a previous session:
notes.txt before:
First note: buy milk.Second note: call mom.
Third note: finish the report.
Running the program to append a fourth line:
Enter the text to append: Fourth note: water the plants.
Text appended to 'notes.txt' successfully.
After the program finishes, notes.txt contains:
notes.txt after:
First note: buy milk.Second note: call mom.
Third note: finish the report.
Fourth note: water the plants.
If notes.txt had not existed, the program would have created it with only the new line. The append mode creates the file on demand — no NULL error for a missing file.
🔍 Line-by-Line Explanation
| Line / Code | Explanation |
|---|---|
scanf("%99s", filename) |
Reads a filename without spaces. %99s caps the input at 99 characters to prevent overflow. |
while (getchar() != '\n' && !feof(stdin)); |
Discards the leftover newline from the previous scanf. Without this, fgets would immediately read an empty line. |
fgets(text, sizeof(text), stdin) |
Reads a full line, including spaces, up to sizeof(text) - 1 characters. The trailing newline is kept in text, which is what we want. |
fopen(filename, "a") |
Opens the file in append mode. Existing content is preserved; the write position starts at the end of the file. |
if (fp == NULL) |
Detects failure — for example, a read-only directory or a permissions issue. |
fputs(text, fp) |
Writes the entire string. The trailing newline from fgets is included, so the new content ends with a newline. |
fclose(fp) |
Flushes the buffered text to disk and releases the file handle. |
'a' in the fopen mode string is the entire difference between "append" and "overwrite." Using "w" on an existing file would erase its content before writing. This is the #1 file-handling bug in beginner code.
📂 Append Mode vs Write Mode
The difference between the two modes is subtle in code but dramatic in effect:
| Mode | Existing file | Missing file | Write position |
|---|---|---|---|
"w" |
Truncates to 0 bytes | Creates it | Start of file |
"a" |
Preserves content | Creates it | End of file |
"w+" |
Truncates to 0 bytes | Creates it | Start (read/write) |
"a+" |
Preserves content | Creates it | End (read/write) |
The same pattern applies to binary mode: "ab" for appending binary data, "wb" for overwriting binary data. See Assignment 3 for the binary version.
🐛 Common Pitfalls
- Using
"w"by mistake: This is the single most common bug. The file opens successfully but its content is erased. If you don't see the old content after running the program, you used"w". - Leftover newline from
scanf: Afterscanf("%s"), a newline is left instdin. If you callfgetswithout flushing it first, you'll read an empty line. Thewhile (getchar() != '\n')loop fixes this. - Forgetting the trailing newline: If the existing file ends with text but no newline, the appended text will be glued to the last line. Either ensure the existing file ends with
\n, or prepend'\n'to the new text. - Missing
NULLcheck: Append mode still fails if the directory is not writable. Always check the return value. - Not closing: Without
fclose, buffered text may never reach the disk. The file may appear unchanged until the program exits.
💡 Tips & Best Practices
- Use
"a"for logs, journals, and any file that accumulates data. - If you want to append content and then read the file back in the same program, use
"a+"andfseek(fp, 0, SEEK_SET)before reading. - Always check
fopenforNULL, even in append mode. - Consider adding a timestamp or a separator (e.g.,
"\n---\n") between appended entries for readability. - Compile with
gcc -Wall -Wextra -std=c11 -gto catch format-string mistakes.