Add Data to the End of a File in C
To add data to the end of a file in C, you can open the file in append mode using fopen() with the mode "a" or "a+". This allows you to write new data without altering the existing content in the file.
Example 1: Appending Text to a File using fopen() with “a” Mode
In this example, we will open an existing file in append mode ("a") and add a line of text at the end of the file.
main.c
</>
Copy
#include <stdio.h>
int main() {
FILE *fp = fopen("example.txt", "a"); // Open file in append mode
if (fp == NULL) {
perror("Error opening file");
return 1;
}
fprintf(fp, "This is a new line added to the file.\n");
fclose(fp);
return 0;
}
Explanation:
FILE *fp: Declares a file pointer to manage file operations.fopen("example.txt", "a"): Opensexample.txtin append mode. The"a"mode allows new data to be written at the end of the file without modifying its existing content.if (fp == NULL): Checks if the file was opened successfully; if not, it prints an error message.fprintf(fp, "..."): Writes a new line of text into the file.fclose(fp): Closes the file to ensure that all data is properly saved.
Output:
This is a new line added to the file.
Example 2: Appending Data to a File Using fopen() with “a+” Mode
In this example, we will open a file in append mode with read access ("a+"), append data, and then read back the contents of the file to verify the changes.
main.c
</>
Copy
#include <stdio.h>
int main() {
FILE *fp = fopen("example.txt", "a+"); // Open file in append and read mode
if (fp == NULL) {
perror("Error opening file");
return 1;
}
// Append new data to the file
fprintf(fp, "Appending a second line to the file.\n");
// Reset the file position to the beginning to read the contents
fseek(fp, 0, SEEK_SET);
char ch;
// Read and print the entire file content
while ((ch = fgetc(fp)) != EOF) {
putchar(ch);
}
fclose(fp);
return 0;
}
Explanation:
FILE *fp: Declares a file pointer for file operations.fopen("example.txt", "a+"): Opensexample.txtin append and read mode. The"a+"mode allows appending data while also providing the ability to read the file.fprintf(fp, "..."): Appends a new line of text to the file.fseek(fp, 0, SEEK_SET): Resets the file pointer to the beginning so that the file content can be read from the start.while ((ch = fgetc(fp)) != EOF): Reads each character until the end of the file and prints it usingputchar(ch).fclose(fp): Closes the file after all operations are complete.
Output:
Contents of example.txt will include all previous data followed by:
Appending a second line to the file.
Conclusion
In this tutorial, we learned multiple approaches to add data to the end of a file in C:
- Example 1: Demonstrated how to append text using
fopen()in"a"mode. - Example 2: Showed how to use
fopen()in"a+"mode to append data and then read the entire file.
