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.


  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.

Example

#include<stdio.h>
#include<conio.h>

int main(){

   FILE *fp;
   char address[40];
   fp = fopen("D://program.txt", "a");
   if (fp == NULL) 
    {
       printf("Error");
       exit(1);   
    }
    printf("Enter the address you want to append: ");
   gets(address);
 fprintf(fp, "Your address: \n %s", address);
 printf("Successfully Appended \n");
 
 fclose(fp);
 printf("\n Your address is appended to the file. Open and check.");  
getch();
return 0;
}

Output

















No comments:

Post a Comment