File handling in 'C'

File handling in 'C' language :

  • File is a basic storage unit for storing your data into computers. 
  • File stores a data in the form of bytes. Without using file we can not deal with our data in computer system.  
  • Thus it is important to learn how to deal with files using C program.

Introduction to Streams : 
  • As we know that computer is a machine and it stores data in the form of bits/bytes.
  • A sequence of such a bits or bytes is called as stream. 
  • There are three basic types of streams : input stream, output stream and error stream. 
  • Sequence of bytes flows into a program is called input stream. stdin is a standard input stream. 
  • Sequence of bytes moves out from a program is called output stream. stdout is a standard output stream.  
  • A sequence of bytes which refers to an error information is called an error stream. stderr refers to standard error stream.


Types of files :
  • There are basicaly two types of files : text file and binary file.
  • Text file is a file which contains data in a text format. 
  • Binary file is a file which contains binary information  as data. 
  • Binary information refers to information represented using 1's and 0's (Binary - bi means two nary means symbols thus binary means using only two symbols 1 and 0). 


Operations on a text file :
  • We can perform various operations  on a file like writing data to a file, deleting data from a file, appending data to a file, accessing data from a file and so on. 
  • Before performing any operation on a file we have to open file first. 
  • Thus opening file is a basic operation performed on file. C language provides various built-in functions to perform operations on a file. 
  • All these functions are located in stdlib.h header file.


Standard library Input/Output functions:

1) fopen() : This function is used to open an existing file or create a new file. 
It open a file and returns a file pointer to it. Syntax :
FILE *fp=fopen(file_name,mode);
Where
          file_name specifies name of file to be open. 
          mode indicates operating mode of a file. 
Value of mode can be any one of following:
w : opens a text file in a write mode only.
w+ : opens a file text in read as well as write mode.
r : opens a text file in read mode only.
r+ : opens a text file in read as well as write mode.
a : opens a text file in append mode only (writing data at the end of file)
a+ : opens a text file in read and append mode.
rb : opens a binary file in read mode only
rb+ : opens a binary file in both read and write mode.
wb : opens a binary file in write mode only.
wb+ : opens a binary file in both read and write mode.
ab : opens a binary file in append mode only.
ab+ : opens a binary file in both read and append mode. 

  • For example consider following program to illustrate fopen()
#include<stdio.h>
#include<stdlib.h>
int main() {
 FILE *fp;
 //opening file in write mode
 fp=fopen("myfile.txt","w");
 if(!fp)
 printf("\n Error in opening file...");
 else
 printf("\n file opened...");
 return 0;
}

Output :
 file opened...

2) fclose () : This function  is used to close file. 
Syntax : fclose(FILE *fp);  
     where fp is a file pointer returned by fopen function. 
It returns zero on success and EOF (constant defined in stdio.h meaningend of file) if error occurs in closing file.

3) fgetc() : As the name indicates get character this function is used to read a character from a file. 
Syntax : char ch=fgetc(FILE *fp); 
       where fp is file pointer returned by fopen function. 
It returns a character that has been read successfully from a file.

4) fputc() : This function is used to put or write a character to a file. 
Syntax : fputc(ch,fp); 
     where ch is a character to be written to a file and fp is file pointer returned by fopen function.

5) fscanf() : This function is used to read formatted data from a file.
Syntax : fscanf(FILE *fp,const char format, arg1,arg2....);
    Where fp is file pointer  returned by fopen function. Format specifies format of data stored in file. Arguments are arg in which to read actual data.

6) fprintf() : It is used to write formatted data to a file. 
Syntax : fprintf(FILE *fp,const char format,arg1,arg2,....);
     Where fp is file pointer, format specifies data format and args specifies arguments containing data.

7) getw() : It is used to read an integer from a file. 
Syntax int number = getw(FILE *fp);

8) putw() : It is used to write an integer to a file. 
Syntax : putw(int number, FILE *fp);

Program to illustrate fputc and fgetc functions :
#include<stdio.h>
#include<stdlib.h>
int main()
{
 FILE *fp;
 char ch;
 //to illustrate fgetc and fputc
 fp=fopen("myfile.txt","w");
 if(!fp)
 printf("\n Error in opening file...");
 fputc('I',fp);
fclose(fp);
fp=fopen("myfile.txt","r");
 ch=fgetc(fp);
 printf("File contains : %c",ch);
 return 0;
}

Output :
File contains : I

Note : Here we open file myfile.txt in write mode then we write character I to it using fputc(). We close file and reopen it again in read mode to set file pointer at beginning (we do it in further programs also). We read character from file and display it.


Program to illustrate getw and putw functions :
#include<stdio.h>
#include<stdlib.h>
int main() {
 FILE *fp;
 int num=78,n;
 //to illustrate getw and putw
 fp=fopen("file1.txt","w");
 putw(num,fp);
 fclose(fp);
 fp=fopen("file1.txt","r");
 n=getw(fp);
 printf("n=%d",n);
 return 0;
}

Output :
n=78


Program to illustrate fprintf and fscanf functions  :
#include<stdio.h>
#include<stdlib.h>
int main() 
{
 FILE *fp;
 char s1[30],s2[30];
 //to illustrate fprintf and fscanf
 fp=fopen("f1.txt","a");
 fprintf(fp,"%s %s","Hello","Welcome");
 fclose(fp);
 fp=fopen("f1.txt","r");
 fscanf(fp,"%s %s",s1,s2);
 printf("File data is :\n");
 printf("%s %s",s1,s2);
 return 0;
}

Output :
File data is :
Hello Welcome


Random access to file : 
C language provides following three functions to support random access to the file.

1) ftell() :

  • This function tells about current location of file pointer. 
  • It returns the position from start of file at where file pointer is located currently.
  • Syntax : ftell(FILE *fp);
fp is pointer returned by fopen function.


2) fseek() :

  • This function is used to move a file pointer at certain position. 
  • Syntax  : fseek(FILE *fp,int displacement, int mod);
  • where fp is file pointer returned by fopen function.
  • displacement indicates number of bytes to move pointer forward(if positive value) or backward (if negative value).
  • mod can be 0,1 or 2. If mod is 0 then displacement is counted from beginning of a file. If mod is 1 then displacement is counted from current position of a file pointer. If mod is 2 then displacement is counted from end of file.


3) rewind() : 

  • This function is used to set file pointer at beginning of file.
  • Syntax : rewind(FILE *fp);


For example : Consider following program 

#include<stdio.h>
#include<stdlib.h>
int main()
{
 char ch;
 FILE *fp;
 fp=fopen("file.txt","w");
 fprintf(fp,"%s","Hello....");
 fclose(fp);
 fp=fopen("file.txt","r");
 while((ch=fgetc(fp))!=EOF)
 printf("%c",ch);
 //current location of file ptr
 printf("\nfp is currently at : %c",fgetc(fp));
 //setting pointer at beginning
 rewind(fp);
 printf("\n fp is now at %c",fgetc(fp));
 //moving file pointer 4 bytes ahead
 fseek(fp,4,0);
 ch=fgetc(fp);
 printf("\n After moving 4 bytes ahead current char under pointer = %c",ch);
 fseek(fp,-2,1);
 ch=fgetc(fp);
 printf("\nAfter moving 2 bytes backwardcurrent character = %c",ch);
return 0;
}

Output : 
Hello....
fp is currently at : �
fp is now at H
After moving 4 bytes ahead current char under pointer = o
After moving 2 bytes backwardcurrent character = l

Note : After reading data file pointer is at the end of file.

Comments

Popular posts from this blog

Write a program to allocate memory dynamically for n integers. Accept the elements and calculate their sum and average

C program to accept names of n cities and search for city named “Pune”.