In this tutorial, we will write a C program to append data into a file. Before that, you may go through the following C topics.
Appending data means adding an additional data at the end of the file such as:
test.txt: Hello!
New Data: This is simple2code.com
After appending the new data to the file, it will look something like this,
test.txt:
Hello!
This is simple2code.com
C Program to append data to a text file
Explanation: We will first open the file, if the file does not exist then the program will automatically create a file for you. Then the program will ask for the data to enter.
If there is some data already present in the file then the newly entered data will be added at the end of the file.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | #include <stdio.h> #include <stdlib.h> int main() { FILE * fp; char data[1000]; fp = fopen("test.txt", "a"); printf("Enter data to append: "); fgets(data, 1000, stdin); fputs(data, fp); printf("File appended successfully"); fclose(fp); // Again open the file to display fp = fopen("test.txt", "r"); printf("\nNew Content:\n"); char ch; while ((ch = fgetc(fp)) != EOF) { printf("%c", ch); } fclose(fp); return 0; } |
Output: After the successful execution of the program for appending data into a file in C, we get,
Before and after the execution of the program, the data present in the test.txt:
Before:
Hello!
After:
Hello!
This is simple2code.com