How to Append to a File in C: Simple Guide with Example
To append to a file in C, open the file using
fopen with the mode "a" or "a+". Then use fprintf or fwrite to add data, and finally close the file with fclose.Syntax
Use fopen with mode "a" to open a file for appending. This mode creates the file if it doesn't exist and moves the write position to the end of the file.
FILE *fopen(const char *filename, const char *mode);"a": Open for writing at the end (append)."a+": Open for reading and appending.
After opening, use fprintf or fwrite to write data, then close with fclose.
c
FILE *file = fopen("filename.txt", "a"); if (file != NULL) { fprintf(file, "text to append\n"); fclose(file); }
Example
This example opens a file named example.txt in append mode, writes a line of text, and closes the file. If the file doesn't exist, it will be created.
c
#include <stdio.h> int main() { FILE *file = fopen("example.txt", "a"); if (file == NULL) { perror("Error opening file"); return 1; } fprintf(file, "Hello, this line is appended!\n"); fclose(file); return 0; }
Common Pitfalls
Not checking if the file opened successfully can cause your program to crash or behave unexpectedly. Always check if fopen returns NULL.
Using "w" mode instead of "a" will overwrite the file instead of appending.
Forgetting to close the file with fclose can cause data loss or resource leaks.
c
#include <stdio.h> int main() { // Wrong: overwrites file FILE *file = fopen("example.txt", "w"); if (file == NULL) return 1; fprintf(file, "This overwrites the file\n"); fclose(file); // Right: appends to file file = fopen("example.txt", "a"); if (file == NULL) return 1; fprintf(file, "This appends to the file\n"); fclose(file); return 0; }
Quick Reference
"a": Append write only, creates file if missing."a+": Append read/write, creates file if missing.- Always check if
fopenreturnsNULL. - Use
fprintforfwriteto write data. - Close file with
fcloseto save changes.
Key Takeaways
Open the file with mode "a" in fopen to append data without erasing existing content.
Always check if fopen returns NULL to handle file open errors safely.
Use fprintf or fwrite to write data after opening the file in append mode.
Close the file with fclose to ensure data is saved and resources are freed.
Avoid using "w" mode when you want to add to a file instead of overwriting it.