Explain read 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 read mode of opening the file, use the following syntax −

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

If the file does not exist, then fopen function returns NULL value.

If the file exists, then data is read successfully from file.

Example

Following is the C program for opening a file in read 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"); // already existing need to be open in read mode
   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 lines are: %d\n",linesCount);
   return 0;
}

Output

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

Total number of lines are: 3
raja
Published on 24-Mar-2021 17:53:44
Advertisements