C Program File Handling – How to Read and Write using fscanf fprintf fgets fputs functions

Basically a file represents a sequence of bytes on the disk where a group of related data is stored. File is created for permanent storage of data. 
In C Programming, we can create files on secondary media i.e hard disk and store data in either text or binary format. In text format, everything in a file is considered in character format and each character requires 1 byte. so to store a number 32555. it is 5 digit number, every digit is considered as character so 5 characters means 5 bytes requires to store in text format.
In Binary Mode, everything in file is stored in binary format, i.e in form of 0 or 1. so to store number 32555, it can fit in integer type variable. Integer type variable requires 2 bytes only. This mode is preferred for storing record variables.
File Operations

In C, you can perform four major operations on the file, either text or binary:

To write data or store data or record in file.

Creating a new file

FILE *fp;

fp= fopen("myfile.txt","w");

Here fp is FILE type pointer variable, FILE is pre defined structure in stdio.h.

FILE is built in structure provided, we have to use a structure pointer of FILE type to declare a file.

fopen is built in function, it create or open file for writing or reading. it accepts two parameter – filename and opening mode. myfile.txt is the name of file and w is open file in write mode, that means it create a new file or if file exists then it replace it.

C provides a number of functions that helps to perform basic file operations.

Creating new or Opening existing file

The fopen() function is used to create a new file or to open an existing file.
 
General Syntax :
*fp = FILE *fopen(const char*filename, const char*mode);
 
Here filename is the name of the file to be opened and mode specifies the purpose of opening the file. Mode can be of following types, *fp is the FILE pointer (FILE *fp), which will hold the reference to the opened (or created) file.

There are several file opening mode as :

  • r opens a text file in reading mode
  • w opens or create a text file in writing mode.
  • a opens a text file in append mode
  • r+ opens a text file in both reading and writing mode
  • w+ opens a text file in both reading and writing mode
  • a+ opens a text file in both reading and writing mode
  • rb opens a binary file in reading mode
  • wb opens or create a binary file in writing mode
  • ab opens a binary file in append mode
  • rb+ opens a binary file in both reading and writing mode
  • wb+ opens a binary file in both reading and writing mode
  • ab+ opens a binary file in both reading and writing mode

To Close File :

The fclose() function is used to close an already opened file.

General Syntax :

int fclose( FILE *fp );

Here fclose() function closes the file and returns zero on success, or EOF. if there is an error in closing the file. This EOF is a constant defined in the header file stdio.h.

To Write data in file

In Text mode, We can write data using functions as

  • fprintf
  • fputs
  • fputc

How to Write Data using fprintf

#include<stdio.h>

//file handling in C

int main()
{
	FILE *fp;

	int ht=150;
	char nm[100]="stevejobs";

	fp=fopen("data-file1.txt","w");

        if(fp == NULL) 
        {
              printf("Error opening file"); return(-1); 
        } 
	fprintf(fp,"%s\n",nm);
	fprintf(fp,"%d\n",ht);
	fclose(fp);

	
}

How to Write Data using fputs

Syntax

int fputs(const char *str, FILE *stream)

Example:

#include <stdio.h>
int main () 
{
   FILE *fp;
 

   fp = fopen("data-file2.txt", "w");
 
    if(fp == NULL) 
    {
        printf("Error opening file"); return(-1); 
    }   
   

   fputs(" Learning C Programming Language !",fp);
   fputs(" file handling in c",fp);
   fputs(" digitalpadm.com ",fp);
   fclose(fp);
   
   return(0);
}

How to Write Data using fputc

Syntax

int fputc(int char, FILE *stream)

Example

#include <stdio.h>

int main () 
{
   FILE *fp;
   int x;

   fp = fopen("data-file3.txt", "w");
   
   if(fp == NULL) 
   {
          printf("Error opening file"); return(-1); 
   } 
   for( x = 65 ; ch <= 90; ch++ ) 
   {
      fputc(ch, fp);
   }
   fclose(fp);
   return(0);
}

output

download code:

 

To Read Data or Fetch Data from File.

  1. Opening an existing file
  2. Read data from file
  3. Closing a file
In Text mode, We can read data using various functions as
  • fscanf
  • fgets
  • fgetc

How to Read File using fscanf

Syntax
int fscanf(FILE *stream, const char *format, ...)

Example:

#include<stdio.h>

//file handling in C

void main()
{
	FILE *fp;

	int ht;
	char nm[100];

	fp=fopen("data-file1.txt","r");
        if(fp == NULL) 
        {
            printf("Error opening file"); return(-1); 
        } 
	fscanf(fp,"%s",nm);
	fscanf(fp,"%d",&ht);
	fclose(fp);

	printf("\n\t Data from file: \n");
	printf("\n\t NAME  : %s",nm);
	printf("\n\t HEIGHT: %d\n",ht);

	
}

How to Read file using fgets()

#include <stdio.h>

int main () {
   FILE *fp;
   char str[100];

   /* opening file for reading */
   fp = fopen("data-file2.txt" , "r");
   if(fp == NULL) {
      printf("Error opening file");
      return(-1);
   }
   if( fgets (str, 100, fp)!=NULL ) {
      printf(" Data from file : \n%s"str);
   }
   fclose(fp);
   
   return(0);
}

To Read file using fgetc

#include<stdio.h>
int main() 
{
   FILE *f;
   char s;
   clrscr();
   f=fopen("data-file3.txt","r");

   while((s=fgetc(f))!=EOF) 
   {
      printf("%c",s);
   }
   
   fclose(f);
   
return 0;
}
Download code File-Handling-C-Demo-Programs.zip (4 downloads)