Professional Documents
Culture Documents
File Handling
9.1 Introduction
File is a data structure which helps us to store our data permanently on the secondary storage
devices such as hard disk, floppy disk, or CD etc. This is important because the computer memory
is volatile in nature and also large data cannot display on the screen at a time.
The files accessed through the library functions are called Stream Oriented files and the files
accessed with system calls are known as System Oriented files.
Text streams are composed of a set of lines. Each line has zero or more characters and is
terminated by a new line character. Text streams consist of printable characters, the tab character,
and the new-line character. Conversions may occur on text streams during input and output.
Spaces cannot appear before a newline character, a text stream removes these spaces even though
implementation defines it. A text stream, on some systems, may be able to handle lines of up to
254 characters long (including the terminating new line character).
Binary streams are composed of only 0’s and 1’s. It is simply a long series of 0’s and 1’s. More
generally, there need not be a one-to-one mapping between characters in the original file and the
characters read from or written to a text stream. But in the binary stream there will be one-to-one
mapping because no conversion exists, and all characters will be transferred as such.
Most programs need to read and write data to disk based storage systems. Similarly C facilitates us
to perform input and output operations (I/O) to a disk system. Disk I/O operations are performed
on ‘files’. C language can read and write files in a variety of different ways. They are character,
string, formatted and record I/O.
Character I/O: First, data can be read or written one character at a time. Library functions
such as getc() and putchar() read the data from the keyboard and write it to the screen.
String I/O: Secondly data can be read or written as strings, with functions such as gets()
and puts() with keyboards and display screen.
For example:
FILE *fp;
fp = fopen(“name”, “mode”);
fscanf(fp, "format string", variable list);
fprintf(fp, "format string", variable list);
fclose(fp );
Function Operations
fopen () After creating new file, it opens an existing file for use. The fopen() returns the file
pointer position for successful open and returns NULL, if the file does not open or
the file does not exist.
fclose () Close a file which has been opened for use. The fclose() returns zero for successful
close and returns EOF (end of file) when error is encountered in closing a file. By
default, all the files opened are closed when the program is terminated. It is good to
close all the files opened with fopen(), because files can be reopened only if they are
closed.
putc () Write a character to a file.
Syntax: = putc (char_variable, file_pointer)
For example: putc (c, fp);
getc () Read a character from a file.
Syntax: char_variable = getc (file_pointer)
For example: c = getc (fp);
putw () Write an integer to a file.
Syntax: = putw (int_variable, file_pointer)
For example: putw (2, fp);
getw () Read an integer from a file.
Syntax: int_variable = getw (file_pointer)
For example: 2 = getw (fp);
fprintf () Write a set of data value to a file.
Syntax: fprintf(file_pointer,“data_format”, variable_list);
For example: fprintf (fp, “%s %d”, name, roll_no);
fscanf () Read a set of different data type value from a file.
Note:
The input function used to write a variable to a file opened at w-mode:
putc () = putw () = fscanf () = scanf ()
The output function used to read a character from a file opened in r-mode:
getc () = getw () = fprintf () = printf ()
The file pointer moves one by one variable position in every operations of input-output.
The input function will return a EOF (end of file) marked when the end of file has been
reached. For EOF, ctrl + z (^z) is used.
MS-DOS supports file name not more than 8-character and windows supports file name not
more than 256 characters.
Spaces are not allowed in between the file name in MS-DOS mode whereas it is allowed in
windows environment.
Any alphanumeric characters such as a, b, c, … 1, 2, 3,… are accepted.
A. Creating a file
Before performing any task on file, we must create a new file.
Syntax: FILE *file_pointer_name; //FILE must be in capital letter
Example: FILE *fp;
B. Opening a file
Before we can write a file to disk, or read it, we must open it. Opening a file establishes an
understanding between our program and the operating system. This may be the opening mode
of file, operation on file etc.
Syntax: file_pointer_name = (“file_name”, “Opearion_mode”);
Example: FILE *fptr; //creating a file
fptr=fopen(“abc.txt”,”w”); //opening a file
C. Closing a file
When all the input-output operations on a file are completed, we need to close it. Closing a file
means all the links to the file is broken. This is carried out with the statement:
fclose(fptr); //where, fptr is the file pointer of FILE
Examples:
A. Opening a file
Example:
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
int main( )
{
FILE *fp ;
char ch ;
fp = fopen ( "PR1.C", "r" ) ;
while ( 1 )
Note: On execution of this program it displays the contents of the file ‘PR1.C’ on the screen
one character at a time on pressing the enter key.
Note that each string is terminated by hitting enter. To terminate the execution of the program,
hit enter at the beginning of a line. This creates a string of zero length, which the program
recognizes as the signal to close the file and exit.
Example: Reads strings from the file and displays them on screen
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <string.h>
int main( )
{
FILE *fp ;
char s[80] ;
fp = fopen ( "POEM.TXT", "r" ) ;
if ( fp == NULL )
{
puts ( "Cannot open file" ) ;
getch();
exit(1) ;
}
while ( fgets ( s, 79, fp ) != NULL )
printf ( "%s" , s ) ;
getch();
fclose ( fp ) ;
return 0;
}
Example: Read records from a file using structure (EMPLOYEE.DAT is already created)
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
/* Read records from a file using structure */
int main( )
{
FILE *fp ;
struct emp
{
char name[40] ;
int age ;
float bs ;
} ;
struct emp e ;
fp = fopen ( "EMPLOYEE.DAT", "r" ) ;
if ( fp == NULL )
{
puts ( "Cannot open file" ) ;
getch();
exit(1) ;
}
while ( fscanf ( fp, "%s %d %f", e.name, &e.age, &e.bs ) != EOF
)
printf ( "\n%s %d %f", e.name, e.age, e.bs ) ;
getch();
fclose ( fp ) ;
}
Example: WAP to copy a file and rewrite in another file using fgets() and fputs().
#include<stdio.h>
#include<conio.h>
void main()
{
char line[251];
FILE *fp1,*fp2;
clrscr();
fp1=fopen("my.txt","r");
fp2=fopen("copy.txt","w");
while(fgets(line,6,fp1)!=NULL)
{
Example: WAP to write information to a file and read from using formatted I/O.
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char choice;
char name[40];
int age;
float height;
FILE *fptr;
fptr=fopen("myname.dat","w+");
do
{
clrscr();
printf("Enter name:");
scanf("%s",name);
Programming in C - Compiled by Yagya Raj Pandeya, NAST, Dhangadhi ©yagyapandeya@gmail.com Page 10
Note: The statement fflush(stdin);is used to buffer the input data and hence finally
display all the contents at all.
Example: WAP identify the size of file using of fseek() and ftell().
#include <stdio.h>
#include <conio.h>
long filesize(FILE *fptr);
int main(void)
{
FILE *fptr;
clrscr();
fptr = fopen("c:\\MYFILE.TXT", "w+");
fprintf(fptr, "This is a test");
printf("Filesize of MYFILE.TXT is %ld bytes\n",
filesize(fptr));
fclose(fptr);
return 0;
}
curpos = ftell(fptr);
fseek(fptr, 0L, SEEK_END);
length = ftell(fptr);
fseek(fptr, curpos, SEEK_SET);
return length;
}