Computer >> Computer tutorials >  >> Programming >> C programming

Why files are needed in C programming language?


Files is collection of records (or) it is a place on hard disk, where data is stored permanently. By using C commands, we access the files in different ways.

Need of files in C language

  • Entire data is lost when the program terminates and storing in a file will preserve your 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.

  • If you have a file containing all the data, you can easily access the contents of the file by using few commands in C.

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

Operations on files

The operations that can be carried out on files in C 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 opening and naming file is as follows −

FILE *File pointer;

For example, FILE * fptr;

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

For example, fptr = fopen ("sample.txt”, "r”)

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

The syntax for reading from fileis as follows −

int fgetc( FILE * fp );// read a single character from a file

The syntax for writing into file is as follows −

int fputc( int c, FILE *fp ); // write individual characters to a stream

Example

Following is the C program to demonstrate the files −

#include<stdio.h>
void main(){
   //Declaring File//
   FILE *femp;
   char empname[50];
   int empnum;
   float empsal;
   char temp;
   //Opening File and writing into it//
   femp=fopen("Employee Details.txt","w");
   //Writing User I/p into the file//
   printf("Enter the name of employee : ");
   gets(empname);
   //scanf("%c",&temp);
   printf("Enter the number of employee : ");
   scanf("%d",&empnum);
   printf("Enter the salary of employee : ");
   scanf("%f",&empsal);
   //Writing User I/p into the file//
   fprintf(femp,"%s\n",empname);
   fprintf(femp,"%d\n",empnum);
   fprintf(femp,"%f\n",empsal);
   //Closing the file//
   fclose(femp);
   //Opening File and reading from it//
   femp=fopen("Employee Details.txt","r");
   //Reading O/p from the file//
   fscanf(femp,"%s",empname);
   //fscanf(femp,"%d",&empnum);
   //fscanf(femp,"%f",&empsal);
   //Printing O/p//
   printf("employee name is : %s\n",empname);
   printf("employee number is : %d\n",empnum);
   printf("employee salary is : %f\n",empsal);
   //Closing File//
   fclose(femp);
}

Output

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

Enter the name of employee : Pinky
Enter the number of employee : 20
Enter the salary of employee : 5000
employee name is : Pinky
employee number is : 20
employee salary is : 5000.000000