by Dinesh Thakur Category: File Handling

Appending to a file means adding at the end of the file while keeping the previous contents of the file intact. For this the file open mode is "a". Program illustrates appending a file.

#include <stdio.h>

#include <stdlib.h>
void main()
{
   FILE* fptr;
   char ch;
   fptr = fopen("File1.txt", "w");
   clrscr();
   if(fptr ==NULL)
   {
      printf("File1 could not be opened.");
      exit (1);
   }
   else
    {
       printf("File1 is open. Enter a sentence.\n");
       while ((ch= getchar()) != EOF)
       fputc(ch, fptr);
       fclose(fptr);
    }
       fptr = fopen("File1", "a");
       if (fptr == NULL)
       {
         printf("File1 could not be opened");
         exit(1);
       }
       else
       {
          printf("File1 is open for appending.\nWrite a sentence.\n");
          while ((ch= getchar()) != EOF)
            fputc(ch, fptr);
            fclose(fptr);
       }
       fptr = fopen("File1", "r");
       printf("After appending contents of File1 are as below.\n");
       while ((ch = fgetc (fptr)) != EOF)
          printf("%c",ch);
          fclose(fptr);
}

Appending Text in a File in C



About Dinesh Thakur

Dinesh ThakurDinesh Thakur holds an B.SC (Computer Science), MCSE, MCDBA, CCNA, CCNP, A+, SCJP certifications. Dinesh authors the hugely popular blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps. For any type of query or something that you think is missing, please feel free to Contact us.