C Program: Append Data to an Existing File

Appending data to an existing file is a common C operation used for logging, saving records, or adding entries without overwriting existing content. This program opens the file in append mode ("a") using fopen(), which creates the file if it doesn not exist or positions the file pointer at the end if it does. The user is input is written using fprintf() or fputs(). Finally, fclose() saves changes and releases the file. This example teaches safe file handling, mode selection, and writing formatted text to persistent storage essential skills for real world C applications.

Program

#include <stdio.h>
#include <stdlib.h>

int main() {
   FILE *file;
   char text[256];

   file = fopen("data.txt", "a");   // "a" = append mode
   if (file == NULL) {
       printf("Error: Could not open file. ");
       return 1;
   }

   printf("Enter text to append: ");
   fgets(text, sizeof(text), stdin);

   fprintf(file, "%s", text);       // write to file

   fclose(file);
   printf("Data appended successfully. ");

   return 0;
}

Example

Before — data.txt:

First line

Run the program:

Enter text to append: Second line
Data appended successfully.

After — data.txt:

First line
Second line

Run it again and add Third line — the file keeps growing without losing previous content.

19 Views