Explain append mode operation of files in C language

CServer Side ProgrammingProgramming

File is collection of records or is a place on hard disk, where data is stored permanently.

Need of files

  • Entire data is lost when a program terminates.

  • Storing in a file preserves the data even if, the program terminates.

  • If you want to enter a large amount of data, normally it takes a lot of time to enter them all.

  • We can easily access the content of files by using few commands.

  • You can easily move your data from one computer to another without changes.

  • By using C commands, we can access the files in different ways.

Operations on files

The operations on files in C programming language are as follows −

  • Naming the file
  • Opening the file
  • Reading from the file
  • Writing into the file
  • Closing the file

Syntax

The syntax for declaring a file pointer is as follows −

FILE *File pointer;

For example, FILE * fptr;

The syntax for naming and opening a file pointer is as follows −

File pointer = fopen ("File name", "mode");

For example, to append mode of opening a file, use the syntax given below −

FILE *fp;
fp =fopen ("sample.txt", "a");

If the file doesn’t exist, then, a new file will be created.

If the file exists, the current content will be added to the old content.

Program

Following is the C program for opening a file in append mode and counting number of lines present in a file −

 Live Demo

#include<stdio.h>
#define FILENAME "Employee Details.txt"
int main(){
   FILE *fp;
   char ch;
   int linesCount=0;
   //open file in read more
   fp=fopen(FILENAME,"r");
   if(fp==NULL){
      printf("File \"%s\" does not exist!!!\n",FILENAME);
      return -1;
   }
   //read character by character and check for new line
   while((ch=getc(fp))!=EOF){
      if(ch=='\n')
         linesCount++;
   }
   //close the file
   fclose(fp);
   //print number of lines
   printf("Total number of before adding lines are: %d\n",linesCount);
   fp=fopen(FILENAME,"a"); //open fine in append mode
   while((ch = getchar())!=EOF){
      putc(ch,fp);
   }
   fclose(fp);
   fp=fopen(FILENAME,"r");
   if(fp==NULL){
      printf("File \"%s\" does not exist!!!\n",FILENAME);
      return -1;
   }
   //read character by character and check for new line
   while((ch=getc(fp))!=EOF){
      if(ch=='\n')
         linesCount++;
   }
   //close the file
   fclose(fp);
   //print number of lines
   printf("Total number of after adding lines are: %d\n",linesCount);
   return 0;
}

Output

When the above program is executed, it produces the following result −

Total number of lines before adding lines are: 3
WELCOME to Tutorials
Its C Programming Language
^Z
Total number of after adding lines are: 8
raja
Published on 24-Mar-2021 13:24:55
Advertisements