Quantcast
Channel: C Programming Archives - QnA Plus
Viewing all articles
Browse latest Browse all 93

C Program to Append to a File

$
0
0

In the previous article, we saw how to write something in a text file. In that case, the previous content, if any, will be overwritten. If there is something in the file to begin with, that content will no longer be present after the new content is written.

Here we’ll see how to add new content at the end of a file. Whatever is already present in the file will be preserved.

Logic to Append to a File

  • Declare a file pointer variable, FILE *fp.
  • Open a file using the fopen() function. This function takes the file name as input and the open mode. Specify the open mode as “w+” for writing. The file specified by the name will be opened. If the file is not present, then it will be created.
  • Write to the file using functions like fprintf(), fputs() etc.
  • 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 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 first takes the address as input. Then it takes the name of the file. The file is opened in append mode. The provided address is appended at the end of the file.

Output of the program:

$ 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.

If we check the file, we can see the new content is present in the file.

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

The post C Program to Append to a File appeared first on QnA Plus.


Viewing all articles
Browse latest Browse all 93

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>