BCA Paper-V Unit-10
BCA Paper-V Unit-10
Lesson Structure
10.0 Objective
10.2 File Handling in C Using File Pointers
10.2.1 Open a file using function fopen()
10.2.2 Close a file using the function fclose()
10.3 Input and Output using pointers
10.3.1 Character Input and Output in files
10.3.2 String Input/Output function
10.3.3 Formatted Input/Output Functions
10.3.4 Block Input/Output Functions
10.4 Sequential vs Random Access Files
10.5 Positioning the File Pointer
10.6 Summary
10.7 Questions for exercise
10.8 Suggessted Readings
10.0 Objective
237
Files
10.1 Introduction
A file is a collection of data stored on secondry storage device like hard disk. Till now,
we had been processing data that was entered through the computers keyboard. This task
become tedious especially when there is huge amount of data to be processed. A better
solution, therefore, is to combine all the input data into a file and then design a program to
read this data from the file whenever required.
A file is a place on the disk where a group of related data is stored. Like most other
languages C supports a number of functions that have the ability to perform basic file
operations, which include.
Naming a file
Opening a file
Reading data from a file
Writing data to a file
And closing a file
The examples we have seen so far in the previous units deal with standard input and
output. When data is stored using variables, the data is lost when the program exits unless
something is done to save it. This unit discusses methods of working with files, and a data
structure to store data. C views file simply as a sequential stream of bytes.
Each file ends either with an end-of-file marker or at a specified byte number recorded
in a system maintained, administrative data structure. C supports two types of files called
binary files and text files.
The difference between these two files is in terms of storage. In text files, everything
is stored in terms of text i.e. even if we store an integer 54; it will be stored as a 3-byte string
- “54\0”. In a text file certain character translations may occur. For example a newline(\n)
character may be converted to a carriage return, linefeed pair. This is what Turbo C does.
Therefore, there may not be one to one relationship between the characters that are read or
written and those in the external device. A binary file contains data that was written in the
same format used to store internally in main memory.
As already mentioned in the above section, a sequential stream of bytes ending with
238
Files
an end-of-file marker is what is called a file. When the file is opened the stream is associated
with the file. By default, three files and their streams are automatically opened when program
execution begins - the standard input, standard output, and the standard error. Streams
provide communication channels between files and programs.
For example, the standard input stream enables a program to read data from the
keyboard, and the standard output stream enables to write data on the screen.
Opening a file returns a pointer to a FILE structure (defined in <stdio.h>) that contains
information, such as size, current file pointer position, type of file etc., to perform operations
on the file. This structure also contains an integer called a file descriptor which is an index into
the table maintained by the operating system namely, the open file table. Each element of
this table contains a block called file control block (FCB) used by the operating system to
administer a particular file.
The standard input, standard output and the standard error are manipulated using file
pointers stdin, stdout and stderr. The set of functions which we are now going to discuss
come under the category of buffered file system. This file system is referred to as buffered
because, the routines maintain all the disk buffers required for reading /writing automatically.
To access any file, we need to declare a pointer to FILE structure and then associate it
with the particular file. This pointer is referred as a file pointer and it is declared as follows :
FILE *fp;
239
Files
To close an open file, the fclose() function is used which disconnects a file pointer from
a file. After the fclose() has disconnected the file pointer from the file, the pointer can be used
to access a different file or the same file but in a different mode. The fclose() function not only
closes the file but also flushes all the bufferes that are maintained for that file. The return value
is 0 if the file is closed successfully or a constant EOF, an end-of file marker, if an error
occurred. This constant is also defined in <stdio.h>. If the function fclose() is not called explicitly,
the operating system normally will close the file when the program execution terminates.
The syntax is :
int fclose( FILE *fp);
Example 2 : write a program to demonstrate to close a file.
#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fp;
fp = fopen(“student.txt”, “r”);
if( fp == NULL)
{
Printf(“\n the file could not be opened”);
exit(1);
}
….
….
fclose( fp);
getch();
}
After opening the file, the next thing needed is the way to read or write the file. There
241
Files
are several functions and macros defined in <stdio.h> header file for reading and writing the
file. These functions can be categorized according to the form and type of data read or written
on to a file. These functions are classified as :
Character input/output functions
· String input/output functions
· Formatted input/output functions
· Block input/output functions.
ANSI C provides a set of functions for reading and writing character by character or
one byte at a time. These functions are defined in the standard library. They are listed and
described below :
· getc()
· putc()
getc( ) is used to read a character from a file and putc( ) is used to write a character to a file.
Their syntax is as follows :
int putc(int ch, FILE *stream);
int getc(FILE *stream);
The file pointer indicates the file to read from or write to. The character ch is formally
called an integer in putc( ) function but only the low order byte is used. On success putc( )
returns a character(in integer form) written or EOF on failure. Similarly getc( ) returns an
integer but only the low order byte is used. It returns EOF when end-of-file is reached. getc( )
and putc( ) are defined in <stdio.h> as macros not functions.
fgetc() : the fgetc() function returns the next character from stream,EOF if the end of
file is reached, or if there is an error. The general syntax is:
int fgetc( FILE *stream);
fgetc returns the character read as an int or return EOF to indicate an error or end of
file. fgetc() reads a single character from the current position of a file. After reading the character,
the function increments the associated file pointer to point the next character.
fputc() : the fputc() is opposite of fgetc() and is used to write a character to the stream.
The general syntax is :
int putc( int c, FILE * stream);
242
Files
the fputc() function will write the byte specified by c to the outputstream pointed to by
stream. On successful compilation, fputc() will return the value it has written. Otherwise, in
case of error, the function will return EOF and the error indicator for the stream will be set.
Example 3 : C program to create a file called emp.rec and store information about a person,
in terms of his name, age and salary.
#include <stdio.h>
# include<conio.h>
void main()
{
FILE *fptr;
char name[20];
int age;
float salary;
/* open for writing */
fptr = fopen(“emp.rec”, “w”);
if (fptr == NULL)
{
printf(“File does not exists \n”);
return;
}
printf(“Enter the name \n”);
scanf(“%s”, name);
fprintf(fptr, “Name = %s\n”, name);
printf(“Enter the age\n”);
scanf(“%d”, &age);
fprintf(fptr, “Age = %d\n”, age);
printf(“Enter the salary\n”);
scanf(“%f”, &salary);
fprintf(fptr, “Salary = %.2f\n”, salary);
fclose(fptr);
}
243
Files
O/P:
Enter the name
raj
Enter the age
40
Enter the salary
4000000
Example 4 : C program to illustrate how a file stored on the disk is read
#include <stdio.h>
#include <stdlib.h>
void main()
{
FILE *fptr;
char filename[15];
char ch;
244
Files
fclose(fptr);
}
O/P:
Enter the filename to be opened
Abc.txt
Example 5 : Write a program to copy one file to another.
#include <stdio.h>
main( )
{
FILE *fp1;
FILE *fp2;
int ch;
fp1 = fopen(“student1.txt”,”r”)
if(fp1== NULL)
{
printf (“Error opening input file\n”);
exit(1);
}
Fp2 = fopen(“student2.txt”,”w”)
if(fp2 == NULL)
{
printf(“Error opening output file\n”);
exit(1);
}
while (!feof(fp1))
{
ch=getc(fp1);
putc(ch,fp2);
}
fclose(fp1);
245
Files
fclose(fp2);
}
O/P :
If the file “ student1.txt” is not present, then the output would be:
Error opening input file
If the disk is full, then the output would be:
Error opening output file
If there is no error, then “student2.txt” would contain whatever is present in “student1.txt” after
the execution of the program, if “student2.txt” was not empty earlier, then its contents would be
overwritten.
Example 6 : C Program to Append the Content of File at the end of Another.
#include <stdio.h>
#include <stdlib.h>
main()
{
FILE *fsring1, *fsring2, *ftemp;
char ch, file1[20], file2[20], file3[20];
printf(“Enter name of first file “);
gets(file1);
printf(“Enter name of second file “);
gets(file2);
printf(“Enter name to store merged file “);
gets(file3);
fsring1 = fopen(file1, “r”);
fsring2 = fopen(file2, “r”);
if (fsring1 == NULL || fsring2 == NULL)
{
perror(“Error has occured”);
printf(“Press any key to exit...\n”);
exit(EXIT_FAILURE);
}
246
Files
If we want to read a whole line in the file then each time we will need to call character
input function, instead C provides some string input/output functions with the help of which we
can read/write a set of characters at one time. These are defined in the standard library and
are discussed below :
fgets () : the function fgets() stand for file get string. The fgets() function is used to get
a string from a stream. The general syntax is :
char *fets( char *str, int size, FILE *strem);
247
Files
the fgets() function reads atmost one less than the number of characters specified by
size from the given stream and stores them in the string str. The fgets() terminates as soon as
it encounters either a newline character, EOF, or any other error.
fputs() : fputs is opposite of fgets(), is used to write a line from to a file. The general
syntax is:
int fputs( const char * str, FILE *stream);
the fputs() writes the string pointed to by str to the stream pointed to by stream. On
successful compilation fputs() return 0. In case of error it returns EOF.
Example :
10.3.3 Formatted Input/Output Functions
If the file contains data in the form of digits, real numbers, characters and strings, then
character input/output functions are not enough as the values would be read in the form of
characters. Also if we want to write data in some specific format to a file, then it is not possible
with the above described functions. Hence C provides a set of formatted input/output functions.
These are defined in standard library and are discussed below.
fprintf() : the fprintf() is used to write formatted output to stream. The general syntax is :
int fprintf( FILE *stream, const char *format, …);
the function writes data that is formatted as specified by the formal argument to the
specified stream. The parameter format in the fprintf() is nothing but a C string that contain
the text has to be written on to the stream.
fscanf() : the fscanf() is used to read formatted data from the stream. The general
sybntax is :
int fscanf(FILE *stream, const char *format, ….);
the fscanf() is used to read data from the stream and store them according to the
parameter format into the loc atins pointed by the additional arguments.
10.3.4 Block Input/Output Functions
Block Input / Output functions read/write a block (specific number of bytes )from/to a
file. A block can be a record, a set of records or an array. These functions are also defined in
standard library and are described below.
fread() : the fread() function is used to read data from a file. The general syntax is :
int fread(void *buf, int num_bytes, int count, FILE *fp);
248
Files
fwrite(): the fwrite () function is used to write data to afile. The general syntax is:
int fwrite(void *buf, int num_bytes, int count, FILE *fp);
In case of fread(), buf is the pointer to a memory area that receives the data from the
file and in fwrite(), it is the pointer to the information to be written to the file.
num_bytes specifies the number of bytes to be read or written. These functions are
quite helpful in case of binary files. Generally these functions are used to read or write array of
records from or to a file.
We have seen that C supports two type of files – text and binary files, also two types of
file systems – buffered and unbuffered file system. We can also differentiate in terms of the
type of file access as Sequential access files and random access files. Sequential access
files allow reading the data from the file in sequential manner which means that data can only
be read in sequence. All the above examples that we have considered till now in this unit are
performing sequential access.Random access files allow reading data from any location in
the file. To achieve this purpose, C defines a set of functions to manipulate the position of the
file pointer. We will discuss these functions in the following sections.
To support random access files, C requires a function with the help of which the file
pointer can be positioned at any random location in the file. Such a function defined in the
standard library is discussed below :
The function fseek( ) is used to set the file position. Its prototype is:
Int fseek(FILE *fp, long offset, int pos);
The first argument is the pointer to a file. The second argument is the number of bytes
to move the file pointer, counting from zero. This argument can be positive, negative or zero
depending on the desired movement. The third parameter is a flag indicating from where in
the file to compute the offset. It can have three values :
SEEK_SET(or value 0) the beginning of the file,
SEEK_CUR(or value 1) the current position and
SEEK_END(or value 2) the end of the file
249
Files
These three constants are defined in <stdio.h>. If successful fseek( ) returns zero.
Another function rewind() is used to reset the file position to the beginning of the file. Its prototype
is :
void rewind(FILE *fp);
A call to rewind is equivalent to the call
fseek(fp,0,SEEK_SET);
Another function ftell() is used to tell the position of the file pointer. Its prototype is:
long ftell(FILE *fp);
It returns –1 on error and the position of the file pointer if successful.
10.6 Summary
250
Files
2. fclose()
3. fgets()
4. fputs()
Referenced Link
1. www.programiz.com/c-programming
2. www.tutorialspoint.com/cprogramming
3. www.cprogramming.com
4. en.wikipedia.org/wiki/C_(programming_language)
251