You are on page 1of 11

CHAPTER - 9

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.

All the data stored on disk is in


binary form and the data structure
may varies from one operating
system to another but this will all
manage by the C-library function.

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.

Streams and Files


Streams facilitate a way to create a level of abstraction between the program and an input/output
device. This allows a common method of sending and receiving data amongst the various types of
devices available. There are two types of streams: text and binary.

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.

When a program begins, there are three available streams:


 Standard input (stdin) is the stream
where a program gets its input data
 Standard output (stdout) is the stream
where a program writes its output data.
 Standard error (stderr) is another
output stream typically used by
programs to output error messages.

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.

Programming in C - Compiled by Yagya Raj Pandeya, NAST, Dhangadhi ©yagyapandeya@gmail.com Page 1

Print to PDF without this message by purchasing novaPDF (http://www.novapdf.com/)


 Formatted I/O: Thirdly, data can be read or written in a format generated by printf() and
scanf() functions: as a collection of values that may be mixed characters, strings, floating
point and integer number.
 Record/ Block I/O: Fourthly, data may be read or written in a new format called “record”
or “block”. Record is a fixed length group of data, and is commonly used to store a
succession of similar data items, such as array elements or structures.

9.2 File Operations


C supports various operations on file such as: creating a new file, opening an existing file, reading
data from a file, writing data to a file, moving to a specific location in a file (seeking) and closing a
file. The general logic performed on file can be listed as:
 Define a local ‘pointer’ of type FILE ( called file pointer )
 Open the file and associate it with the file pointer via fopen()
 Perform the I/O operations using file I/O functions ( ex. fscanf() and fprintf() )
 Disconnect the file from the task using fclose()

For example:
FILE *fp;
fp = fopen(“name”, “mode”);
fscanf(fp, "format string", variable list);
fprintf(fp, "format string", variable list);
fclose(fp );

File Handling function on C

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.

Programming in C - Compiled by Yagya Raj Pandeya, NAST, Dhangadhi ©yagyapandeya@gmail.com Page 2

Print to PDF without this message by purchasing novaPDF (http://www.novapdf.com/)


Syntax: fscanf(file_pointer,“data_format”, &variable_list);
For example: fscanf (fp, “%s %d”, name, &roll_no);
fseek () It sets the position to a desired point in the file.
ftell () Give the current position in the file in terms of bytes from the start.
rewind () It sets the position to the beginning of the file.
fwrite() Writing in to a file
Syntax: fwrite (ptr, size, n, fp);
Where:
ptr //pointer to the data block (source)
size //size of each block (number of bytes to be written)
n // number of blocks to be written
fp // file pointer (destination)

fread() Reading from a file


Syntax: fread (&str, size, n, fp);
Where:
&str //destination memory address
size // size of each block (number of bytes to be read)
n // number of blocks to be read
fp // file pointer (source)

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

Programming in C - Compiled by Yagya Raj Pandeya, NAST, Dhangadhi ©yagyapandeya@gmail.com Page 3

Print to PDF without this message by purchasing novaPDF (http://www.novapdf.com/)


File opening modes
Modes Operations
r (read text Reading from existing file and if the file cannot be opened (using
mode) fopen()), it returns NULL.
w (write text If file is exists, the previous contents are erased and new contents is
mode) added (overwrite). If file does not exist, a new file is created.
Returns NULL if unable to open file.
a (append text If the file is existed, the previous contents are preserved and new
mode) contents are also added at the end of file. If the file does not exist, a
new file is created. Returns NULL if unable to open file.
rb read binary mode
wb write binary mode (truncates file to zero length if it already exits or
creates new file)
ab append binary mode for writing (opens or creates file and sets file
pointer to the end-of-file)
r+ (update mode Reading existing contents, writing new contents and modifying
+) existing contents of the file.
w+ Writing new contents, reading them form back side (last to first) and
modifying (arrange) existing contents of the file.
a+ Reading the existing contents, appending new contents to the end of
file but this cannot modify the existing content of file.
r+b or rb+ read and write binary mode
w+b or wb+ read and write binary mode (truncates file to zero length if it already
exists or creates new file)
a+b or ab+ read and write binary mode (opens or creates file and sets file
pointer to the end-of-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 )

Programming in C - Compiled by Yagya Raj Pandeya, NAST, Dhangadhi ©yagyapandeya@gmail.com Page 4

Print to PDF without this message by purchasing novaPDF (http://www.novapdf.com/)


{
ch = fgetc ( fp ) ;
if ( ch == EOF )
break ;
printf ( "%c", ch ) ;
getch();
}
printf ("\n");
fclose ( fp ) ;
return 0;
}

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.

B. Count chars, spaces, tabs and newlines in a file

Example: Count chars, spaces, tabs and newlines in a file


#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
int main( )
{
FILE *fp ;
char ch ;
int nol = 0, not = 0, nob = 0, noc = 0 ;
fp = fopen ( "PR1.C", "r" ) ;
while ( 1 )
{
ch = fgetc ( fp ) ;
if ( ch == EOF )
break ;
noc++ ;
if ( ch == ' ' )
nob++ ;
if ( ch == '\n' )
nol++ ;
if ( ch == '\t' )
not++ ;
}
fclose ( fp ) ;
printf ( "\nNumber of characters = %d", noc ) ;
printf ( "\nNumber of blanks = %d", nob ) ;
printf ( "\nNumber of tabs = %d", not ) ;
printf ( "\nNumber of lines = %d", nol ) ;
getch();
}

Programming in C - Compiled by Yagya Raj Pandeya, NAST, Dhangadhi ©yagyapandeya@gmail.com Page 5

Print to PDF without this message by purchasing novaPDF (http://www.novapdf.com/)


C. A file copy program

Example: A file copy program.


#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
int main( )
{
FILE *fs, *ft ;
char ch ;
fs = fopen ( "pr1.c", "r" ) ;
if ( fs == NULL )
{
puts ( "Cannot open source file" ) ;
exit(1) ;
}
ft = fopen ( "pr2.c", "w" ) ;
if ( ft == NULL )
{
puts ( "Cannot open target file" ) ;
fclose ( fs ) ;
exit(2) ;
}
while ( 1 )
{
ch = fgetc ( fs ) ;
if ( ch == EOF )
break ;
else
fputc ( ch, ft ) ;
}
fclose ( fs ) ;
fclose ( ft ) ;
}

D. String (line) I/O in Files

Example: Receives strings from keyboard and writes them to file


#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <string.h>
int main( )
{
FILE *fp ;
char s[80] ;
fp = fopen ( "POEM.TXT", "w" ) ;
if ( fp == NULL )
{
puts ( "Cannot open file" ) ;
exit(1) ;
}
Programming in C - Compiled by Yagya Raj Pandeya, NAST, Dhangadhi ©yagyapandeya@gmail.com Page 6

Print to PDF without this message by purchasing novaPDF (http://www.novapdf.com/)


printf ( "\nEnter a few lines of text:\n" ) ;
while ( strlen ( gets ( s ) ) > 0 )
{
fputs ( s, fp ) ;
fputs ( "\n", fp ) ;
}
fclose ( fp ) ;
return 0;
}

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;
}

E. Record Input-Output in FILE

Example: Writes records to a file using structure


#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
int main( )
{
FILE *fp ;
char another = 'Y' ;
struct emp
{
char name[40] ;
int age ;
Programming in C - Compiled by Yagya Raj Pandeya, NAST, Dhangadhi ©yagyapandeya@gmail.com Page 7

Print to PDF without this message by purchasing novaPDF (http://www.novapdf.com/)


float bs ;
} ;
struct emp e ;
fp = fopen ( "EMPLOYEE.DAT", "w" ) ;
if ( fp == NULL )
{
puts ( "Cannot open file" ) ;
exit(1) ;
}
while ( another == 'Y' )
{
printf ( "\nEnter name, age and basic salary: " ) ;
scanf ( "%s %d %f", e.name, &e.age, &e.bs ) ;
fprintf ( fp, "%s %d %f\n", e.name, e.age, e.bs ) ;
printf ( "Add another record (Y/N) " ) ;
fflush ( stdin ) ;
another = getche( ) ;
}
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 ) ;
}

Programming in C - Compiled by Yagya Raj Pandeya, NAST, Dhangadhi ©yagyapandeya@gmail.com Page 8

Print to PDF without this message by purchasing novaPDF (http://www.novapdf.com/)


LAB SECTION

Example: Program to create a text file (character file)


#include <stdio.h>
#include <conio.h>
void main()
{
FILE *fp;
char c;
if ((fp=fopen("sample.dat","w")) !=NULL)
{
while ((c=getchar()) != EOF)
putc(c,fp);
fclose(fp);
}
else
printf("Error in opening a file");
}

Example: Program to read a character data from a text file


#include <stdio.h>
#include <conio.h>
void main()
{
FILE *fp;
char c;
if ((fp=fopen("sample.dat","r")) !=NULL)
{
while ((c=getc(fp)) != EOF)
putchar(c);
fclose(fp);
}
else
printf("Error in opening a file");
getch();

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)
{

Programming in C - Compiled by Yagya Raj Pandeya, NAST, Dhangadhi ©yagyapandeya@gmail.com Page 9

Print to PDF without this message by purchasing novaPDF (http://www.novapdf.com/)


fputs(line,fp2);
printf("%s",line);
}
fclose(fp1);
fclose(fp2);
getch();
}

Example: Program using Block I/O


#include <stdio.h>
#include <conio.h>
void main()
{
FILE *fptr;
struct tag
{
char name[10];
int age ;
}stud[10] , stud1[10];
int i ;
clrscr();
fptr=fopen("ex.dat" , "w" );
for(i=0 ; i<5 ; i++)
scanf("%s %d ",stud[i].name , &stud[i].age);
fwrite(&stud , sizeof(stud[0]) , 5 , fptr);
fclose(fptr);
fptr = fopen("ex.dat" , "r" );
fread(&stud1 , sizeof(stud1[0]) , 5 , fptr);
printf(" \n\n printing the values ");
for(i=0 ; i<5 ; i++)
printf("\n %s \t %d " , stud1[i].name , stud1[i].age);
getch();
}

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

Print to PDF without this message by purchasing novaPDF (http://www.novapdf.com/)


fflush(stdin);
printf("Enter age:");
scanf("%d",&age);
fflush(stdin);
printf("Enter height:");
scanf("%f",&height);
fflush(stdin);
printf("Do you wish to continue:");
scanf("%c",&choice);
fprintf(fptr,"%s\t %d\t %f\n",name,age,height);
}while(choice=='Y' || choice=='y');
rewind(fptr);
printf("\nName\tAge \tHeight");
while(fscanf(fptr,"%s %d %f", name, &age,&height)!=EOF)
printf("\n%s\t %d\t %0.2f",name,age,height);
fclose(fptr);
getch();
}

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;
}

long filesize(FILE *fptr)


{
long curpos, length;

curpos = ftell(fptr);
fseek(fptr, 0L, SEEK_END);
length = ftell(fptr);
fseek(fptr, curpos, SEEK_SET);
return length;
}

Programming in C - Compiled by Yagya Raj Pandeya, NAST, Dhangadhi ©yagyapandeya@gmail.com Page 11

Print to PDF without this message by purchasing novaPDF (http://www.novapdf.com/)

You might also like