C Program to Append to a File

Appending to a means adding the new content at the end of the file retaining the old content intact. If the file is opened in normal write mode, the new content will replace the old content. Here we’ll see how to open a file in append mode

Logic to Append to a File

  1. Declare a file pointer, FILE *fp.
  2. Open the file using the fopen() function. Specify the file name and file opening mode as “a+“. Note: here the file will be opened in read and write mode. The new content will be written after the existing one.
  3. Write to the file using functions like fprintf(), fputs() etc.
  4. Close the file using the fclose() function.

Let’s say, we have a file, info.txt, that already has this content.

$ cat info.txt
Your name: Charges Babbage
Your age: 85

Here is the program to append a new content at the end of the file.

#include <stdio.h>

#define MAX_LINE_LEN 1024

int main() {
  char address[MAX_LINE_LEN];
  char file_name[MAX_LINE_LEN];
  
  FILE *fp;
  
  /*Taking your address as input. These will be appended into a file...*/
  printf("Your address: ");
  gets(address);
  
  /*Taking the file name as input...*/
  printf("Enter the file name to append to: ");
  gets(file_name);
  
  /*Opening the file in appending mode...*/
  fp = fopen(file_name, "a+");
  
  /*File open operation failed.*/
  if (fp == NULL) return -1;
  
  /*Appending your address into the file...*/
  fprintf(fp, "Your address: %s\n", address);
  
  /*Closing the file...*/
  fclose(fp);
  
  printf("Your address is appended to the file %s. Open and check.\n", file_name);
  return 0;
}

This program takes the new content (address) and a file name as input. The specified file is opened in append mode. The printf() function appends the new content at the end of the file.

Output

$ cc -o test test.c
$ ./test
Your address: 44 Crosby Row, Walworth Road, London, England
Enter the file name to append to: info.txt
Your address is appended to the file info.txt. Open and check.

Open the file to check that the new content is added right after the existing one.

$ cat info.txt
Your name: Charges Babbage
Your age: 85
Your address: 44 Crosby Row, Walworth Road, London, England

Author: Srikanta

I write here to help the readers learn and understand computer programing, algorithms, networking, OS concepts etc. in a simple way. I have 20 years of working experience in computer networking and industrial automation.


If you also want to contribute, click here.

Leave a Reply

Your email address will not be published. Required fields are marked *

9
4
2
13
38
9