Lesson13 Files
Lesson13 Files
Files
0
Chapter Outline
Chapter Outline
“Pain is never permanent."
-- St. Teresa of Avila
Introduction.
Introduction.
Types of files.
Types of files.
Basic operations on files.
Basic operations on files.
Random-access files.
Random-access files.
Error-handling
Error-handling
Scratch a dog and you'll find a permanent job.”
Concept of binary files.
-- Franklin P. Jones Concept of binary files.
Conclusion.
Conclusion.
Interview question #2
Why file is also called as an “external data structure”?
Data structure (or Abstract Data Type) is an organized collection of data and operations on that data. It
gives the model of particular organization of data. File is also a data structure that deals with data that
is stored on external storage device (i.e., disk). The data in an external storage device (i.e., secondary
memory) can be brought to internal storage device (i.e., primary memory), various operations such as
read, write and append can be carried out there in primary memory and the changed data can be
brought back to external storage device. Because file is very helpful in doing these activities on
external storage device, we can call it as an “external data structure”.
Interview question #3
Why do we need files?
We need files in order
1. To store data permanently. i.e., the content in the file can never be lost even after program
termination. It can be recalled as and when it is needed.
2. To maintain large amount of data. i.e., it is easy to handle voluminous data during execution.
3. To make disk user-friendly. i.e., the complex interface of disk can be converted to user-friendly
interface by using file so that user can interact with it.
4. To have its storage capacity more. i.e., a file can have its content till there is no space in
storage device.
2 Files
13.2. Types of files
Types of Files
There are two ways to link and access files in a program. These are: by means of library functions and by
means of system-calls of operating system.
1. The files linked and accessed through the library functions are known as stream-oriented files.
These are also called as high-level files, since these involve high-level (programming language
level) functions.
2. It is also possible to link and access files directly by means of an operating system. The system
calls of operating system connect the files with the program. The files linked and accessed using
system calls known as system-oriented files. These are also known as low-level files because
low-level (system level) commands or functions are involved.
Stream-oriented files are supported by C library functions which are common for all operating systems.
But system-oriented files are not at all common to all operating systems because system calls for each
operating system are different.
Stream-oriented files are easier to work with than the system-oriented files because the same library
functions may be used regardless of the device or disk files are involved. Also, the data can be stored in a
manageable form such as one byte at a time.
Stream-oriented files can be subdivided into two categories: text files and binary files. The text files
consist of consecutive characters. These characters can be interpreted as individual data items or as
components of strings or numbers. The manner in which these characters are interpreted is determined
either by the particular library functions used to transfer the information, or by the format specifiers those
start with % with in the library function.
The binary files organize data into blocks containing contiguous bytes of information. These blocks
represent more complex data structures such as arrays and structures. A separate set of library functions
is available for processing these binary files. These library functions provide single instructions that can
transfer entire arrays or structures to or from files. These binary files are very useful to handle file
containing machine language contents, e.g., .exe or .com files.
3 Files
To understand the stream-oriented files, first, it is necessary to understand the concept of stream.
Interview question #3
What do you mean by a stream?
The ANSI standard I/O functions support the stream-oriented files in which input and output are
treated as a continuous stream of bytes. A stream is a source or destination of data that may be
associated with a disk or other I/O devices. The source stream provides data to a program and it is
known as input stream. The destination stream receives the output from the program and is known as
output stream. The generic term I/O stream is used for any file, device or facility on which a
program may perform I/O operations.
An I/O stream can be treated as a flowing sequence of characters. It can be a text stream or
binary stream. A text stream is a sequence of lines of text. In a text stream, each character can be
represented by using ASCII. Each line consists of zero or more characters and a terminating new line
character. ANSI C allows atleast 254 characters in a line. The characters in a text stream may be
modified, added or deleted during I/O operations. A file that contains data written using a text stream
is called a text file. Input from/output to a terminal are mostly performed using text streams. Hence, a
terminal is also associated with the I/O streams in text file.
A binary stream is a sequence of unprocessed bytes. A binary stream, represents raw data
without any conversion unlike a text stream. For example, the character ‘\n’ in a text stream is mapped
to carriage return and line feed. But, in a binary stream, it is never modified. If the data are only stored
as backup for the purpose of reading them afterwards, it is more efficient in using binary streams. A
binary file contains data written in it using binary stream.
All the stream-oriented files (whether text files or binary files) are of two types based on the way of
accessing them. Sequential-access files are the stream-oriented files in which the data can be accessed
sequentially. E.g., if a file contains 100 records and we want to access 57 th record in that file. Then we
should first access all the previous 56 records in sequence and then only we can access 57 th record.
Random-access files are the stream-oriented files in which the data can be accessed directly.
E.g., if a file contains 100 records and we want to access 57 th record in that file, then it is not necessary to
access all the previous 56 records first. We can directly place our file pointer to 57 th record directly. The
random-access files are called as direct-access files.
In order to process the sequential-access file, first we should learn basic operations on files:
4 Files
13.3. Basic operations on files
The standard library in C has many file I/O functions. The file-handling functions in C are easy to use,
powerful and complete. The console I/O functions such as scanf() and printf() help the user to read
from keyboard and write to monitor (The term console refers to keyboard-monitor pair). But the file I/O
functions read from a file and write to another file (or to the same file).
File I/O is always done in a program in the following sequence:
1. Open the file.
2. Read from or write to the file.
3. Close the file.
13.3.1. Opening a file
Before performing any file I/O, the file must be opened. While opening the file, the following are to be
specified:
The name of the file and
The manner (or mode) in which it should be opened (i.e., for reading, writing, reading and writing,
appending at the end of file, or overwriting the file …etc).
The function fopen() is used to open a file. It accepts two strings as arguments with the following form:
FILE *fopen(filename,mode);
From this prototype, it is clear that the function fopen() has:
Arguments:
o file name is the name of the file to opened. As it is a string, it should be enclosed with in double
quotation marks. If we want to specify the full path name for the file, we should use double
backslash (as in DOS) or a single front slash (as in UNIX).
o mode is used to specify the manner in which a file should be opened. As it is a string, it should be
enclosed with in double quotation marks. The possible modes are:
File Opening Meaning
Mode
r (read-only) Open an existing file for reading only.
w(write-only) Open a new file for writing only. If a file with specified filename currently exists, it
will be destroyed and a new file with the same name will be created in its place.
a (append-only) Open an existing file for appending (i.e., for adding new information at the end of
file). A new file will be created if the file with the specified filename does not exist.
r+ (read & write) Open an existing file for update (i.e., for both reading and writing).
w+ (write & read) Open a new file for both writing and reading. If a file with the specified filename
currently exists, it will be destroyed and a new file will be created in its place.
a+(append & read) Open an existing file for both appending and reading. A new file will be created if
the file with specified filename does not exist.
Return value:
On success, fopen() returns a pointer to the predefined structure FILE, whose definition is
available in stdio.h.
On failure, it returns NULL.
5 Files
Ex: FILE *fp; //statement-1
fp=fopen(“sample.txt”,”w”); //statement-2
if(fp==NULL) //statement-3
{
printf(“\n Unable to open a file”);
exit(0);
}
When working with a stream-oriented file, the first step is to establish a buffer area, where the
information is temporarily stored while being transferred between the computer’s memory and the file.
This buffer area allows information to be read from of written to the data file more rapidly. The buffer area
is established by writing:
FILE *fp;
where FILE (upper case letters required) is a special structure type that establishes the buffer area and
fp is a pointer variable that indicates the beginning of the buffer area.
Statement-1 declares fp, the pointer to the pre-defined structure FILE (available in stdio.h). Usually, the
pointer fp is referred to as a stream pointer.
Statement-2 helps us in opening the file sample.txt in writing mode. If there is no file with name
sample.txt in the current directory, then it is created. If already exists, then its content will be erased and
the file is ready for writing the new content. As fopen() returns pointer to the structure FILE, it is handled
with the pointer fp. This pointer will be very helpful in subsequent operations such as read,write…etc.
Statement-3 helps us to handle the failure situation of fopen(). If it is not handled, then there will be
problems such as system crash.
int fputc(character,pointer_to_FILE);
Open the existing file in “w”,“w+”,”a” or “a+” mode using fopen() and handle the file
pointer that is returned.
Read the string from keyboard using gets() or scanf().
Input that string as an argument to the function fgets() along with the file pointer as
follows:
int fputs(string,pointer_to_FILE);
3) writing formatted data to a file: To write formatted data from a file do the following:
Open the existing file in “w”,“w+”,”a” or “a+” mode using fopen() and handle the file
pointer that is returned.
Read the formatted data from keyboard using scanf().
Input that formatted data to function fscanf() along with the file pointer as follows:
7 Files
}s1;
main()
{ FILE *fp;
fp=fopen(“student.dat”,”w”); //step-1:open file in write mode
printf(“\n Enter student details( rno,name,rank and fees):”);
scanf(“%d%s%d%f”,&s1.rno,s1.name,&s1.rank,&s1.fees); //step-2: read content from keyboard
fprintf(fp,”%d\t%s\t%d\t%f”,s1.rno,s1.name,s1.rank,s1.fees); //step-3: write content to file
}
int fgetc(pointer_to_FILE);
a. Open the existing file in “r” or “r+” mode using fopen() and handle the file pointer that is
returned.
b. Use the function fgets() that is used to read a string of specified length from file which has
the following form:
char * fgets(string,size,pointer_to_FILE);
8 Files
o fgets() takes three arguments: first argument is a string, second argument is used to
specify the size of string that is to be read and third argument file pointer.
o fets() reads the next line from the specified file. On success, the string of specified size
that is read will be stored in the first argument. On failure, fgets() returns NULL.
3) Reading formatted data from a file: To read formatted data from a file do the following:
a. Open the existing file in “r” or “r+” mode using fopen() and handle the file pointer that is
returned.
b. Use the function fscanf() that is used to read formatted data (i.e., different forms of data
at a time) from file which has the following prototype:
int fclose(pointer_to_FILE);
9 Files
From this prototype, it is clear that:
o fclose() function takes one argument: the file pointer to which we want to close.
o On success, it returns 0. on failure, it returns EOF.
Ex: FILE *fp;
fp=fopen(“sample.txt”,”w”);
…………..
………….
fclose(fp); //closes the file sample.txt
Program #1
Write a program to create a file, write some text to it and print that text on monitor.
#include<stdio.h>
main()
{
char filename[15],ch;
FILE *fp;
printf(“\n Enter the file name to be created:”);
scanf(“%s”,filename);
fp=fopen(filename,”w”); //first, open file in write mode
if(fp==NULL)
{
printf(“\n unable to open”);
exit(0);
}
printf(“\n Enter some text to file (ctrl+d to end):”);
ch=getchar(); //read a character from key board
while(ch!=EOF) // check that the entered character is not ctrl+d
{
fputc(ch,fp); //write that character to file
ch=getchar(); //again, read a character from key board
}
fclose(fp); // close the file
10 Files
Interview question #4
What do you mean by FILE (all uppercase letters)?
FILE is a predefined structure whose definition is available in stdio.h. It has the following definiton:
typedef struct
{
int level; /*fill/empty level of buffer*/
unsigned flags; /*file status flags*/
char fd; /*file descriptor (file handler)*/
unsigned char hold; /*Ungetc char if no buffer*/
int bsize; /*Buffer size*/
unsigned char _FAR *buffer;/*Data transfer buffer*/
unsigned char _FAR *curp; /*current active pointer*/
unsigned istemp; /*temporary file indicator*/
short token; /*used for validity checking*/
}FILE;
Interview question #5
What are pre-defined streams?
stream Meaning
stdin Standard input device (opened for input).
stdout Standard output device (opened for output).
Write a program
stderr to copy
Standard errorthe content
output deviceof(opened
one filefor
to error
another.
output).
#include<stdio.h>
stdaux
main() Standard auxiliary device (opened for both input and output).
{
stdprn Standard printer (Opened for output).
char source[15],destination[15],ch;
FILEof
The output *fp1,*fp2;
a function like printf() goes to the stream stdout. A function like scanf() receives its input
printf(“\n Enter the an existing file name to be opened:”);
from the stream stdin. We can write to any of the output streams by using functions like fputc(),fputs()
scanf(“%s”,source);
…etc andprintf(“\n Enterany
read from the file name to
of input which thebycontent
streams usingshould be copied”);
functions like fgetc(),fgets()…etc. These streams are
scanf(“%s”,destination);
considered to be files. Usually,
fp1=fopen(source,”r”); stdin
//open is connected
source to mode
file in read the keyboard, stdout and stderr are connected to
if(fp1==NULL)
monitor, stdaux is connected to serial port com1 and stdprn is connected to lpt1.
{
printf(“\n unable to open”);
exit(0);
}
Interviewfp2=fopen(destination,”w”);
question #6 //open destination file in write mode
if(fp2==NULL)
What is the purpose feof()?
{ is a pre-defined function that checks the given stream for an end-of-file indicator. It has the
The feof()
printf(“\n unable to open”);
following form:exit(0);
}
int feof(pointer_to_FILE);
ch=fgetc(fp1); //get a character from source file
while(ch!=EOF)
From this prototype, it //ischeck
clearthat
that:character is not EOF
{
o feof() function takes//write
fputc(ch,fp2); one argument: the file
that character to pointer to which
destination file we want to search for EOF
ch=fgetc(fp1);
character. //Again, read a character from source file
}
On success,
o fclose(fp2); it returns
//close non-zero if an end-of-file character is detected. If end-of-file is not
the file
}
reached, then it returns 0.
Output:
Enter an existing filename to be opened: master.txt
Program #2 file name to which the content should be copied: copy.txt
Enter the
Usually, the content of first file is copied to second 11 file. To check the correctness of Files
program, type the
destination file name by using vi command at $ prompt. If we get the content of source file in
destination file, the program is absolutely correct.
12 Files
Program #3
Write a program to count number of characters, alphabets, digits, white spaces and special
symbols in an existing file.
#include<stdio.h>
main()
{
char filename[15],ch;
FILE *fp;
int ccount,acount,dcount,scount,sscount;
printf(“\n Enter an existing file name to be read:”);
scanf(“%s”,filename);
fp=fopen(filename,”r”); //open an existing file in read mode
if(fp==NULL)
{
printf(“\n Unable to open file”);
exit(0);
}
ccount=acount=dcount=scount=sscount=0; //initially, all counts are 0
ch=fgetc(fp); //read a character from file
while(ch!=EOF)
{
ccount++; //increment character count by 1
if(toupper(ch)>=’A’ &&toupper(ch)<=’Z’) //if it is alphabet
acount++; //increment alphabet count by 1
else if(ch>=’0’ && ch<=’9’) //if it is digit
dcount++; //increment alphabet count by 1
else if(ch==’ ‘ || ch==’\t’ || ch==’\n’) //if it is white space
scount++; //increment space count by 1
else
sscount++; //increment special symbol count by 1
ch=fgetc(fp); //again, read a character from file
}
fclose(fp); //close the file
printf(“\n No.of characters=%d”,ccount);
printf(“\n No.of Alphabets=%d”,acount);
printf(“\n No.of digits=%d”,dcount);
printf(“\n No.of spaces=%d”,scount);
printf(“\n No.of special symbols=%d”,ccount);
}
Output:
Enter an existing filename to be read: master.txt
No.of characters=160
No.of Alphabets=122
No.of digits=2
No.of spaces=30
No.of special symbols=6
13 Files
Program #4
Write a program to write student records to a sequential file and access them
#include<stdio.h>
struct student
{
int rno,rank;
char name[15];
float fees;
struct date_of_birth
{
int day,month,year;
}dob;
}s1;
main()
{
FILE *fp;
char ch;
fp=fopen(“sturecords”,”w”); //create a new file
if(fp==NULL)
{
printf(“\n Unable to open file”);
exit(0);
}
do
{
printf(“\nEnter student details (rno,name,rank,fees and date of birth):”);
scanf(“%d%s%d%f%d%d
%d”,&s1.rno,s1.name,&s1.rank,&s1.fees,&s1.dob.day,&s1.dob.month,&s1.dob.year); //read the student record
from keyboard
fprintf(fp,”%d\t%s\t%d\t%f\t%d/%d/%d”,s1.rno,s1.name,s1.rank,s1.fees,s1.dob.day,
s1.dob.month,s1.dob.year); //write the student record to file
printf(“\n Do u want to add one more record (y/n):”);
scanf(“\n%c”,&ch);
}while(toupper(ch)!=’N’);
fclose(fp);
size_t fwrite(ptr,size,n,pointer_to_FILE);
The function fread() is used to read formatted data from the file. It has the following form:
size_t fread(ptr,size,n,pointer_to_FILE);
From this prototype, it is clear that:
o fread() takes four arguments: ptr is a pointer to the block into which data is read. Size is a
value of type size_t, an unsigned integer, used to hold the length of each item read, in
bytes. n is a value of type size_t, an unsigned integer, used to hold number of data items to
read. Pointer_to_FILE is the pointer to the file in which the data is to be read.
o On success, it returns the number of items (not bytes) actually read. On end-of-file or error,
it returns 0.
Ex: struct student s1;
fread(&s1,sizeof(s1),1,fp);
By using fread() and fwrite() functions, fixed-length records are written or read. By using fprintf() and
fscanf() functions, variable-length records are written or read.
By using fread() and fwrite(), the above program can be modified as follows:
15 Files
Program #5
Write a program to write student records to a sequential file and access them
#include<stdio.h>
struct student
{
int rno,rank;
char name[15];
float fees;
struct date_of_birth
{
int day,month,year;
}dob;
}s1,s2;
main()
{
FILE *fp;
char ch;
fp=fopen(“sturecords”,”w”); //create a new file
if(fp==NULL)
{
printf(“\n Unable to open file”);
exit(0);
}
do
{
printf(“\nEnter student details (rno,name,rank,fees and date of birth):”);
scanf(“%d%s%d%f%d%d
%d”,&s1.rno,s1.name,&s1.rank,&s1.fees,&s1.dob.day,&s1.dob.month,&s1.dob.year); //read the student record
from keyboard
fwrite(&s1,sizeof(s1),1,fp); //write the student record to file
printf(“\n Do u want to add one more record (y/n):”);
scanf(“\n%c”,&ch);
}while(toupper(ch)!=’N’);
fclose(fp);
int fseek(pointer_to_FILE,offset,location);
void rewind(pointer_to_FILE);
ftell() function: The function ftell() is used to get the current file position pointer. It has the following
prototype:
long ftell(pointer_to_FILE);
17 Files
From this prototype, it is clear that:
o ftell() function takes one argument: file pointer.
o on success, it returns the current file pointer position. On error, it returns -1 and sets errno to a
positive value.
Program #6
Write a program to demonstrate fseek(), ftell() and rewind() functions
#include<stdio.h>
main()
{
FILE *fp;
char ch;
fp=fopen("stud.txt","w+");
if(fp==NULL)
{
printf("\n Unable to open file:");
exit(0);
}
printf("\n Enter the text into file (end with ctrl+d):");
ch=getchar();
while(ch!=EOF)
{
fputc(ch,fp);
ch=getchar();
}
ch=fgetc(fp);
while(ch!=EOF)
{
printf("%c",ch);
ch=fgetc(fp);
}
fseek(fp,5,SEEK_SET); //place the cursor at the position 5
printf("\n The cursor is at %d position",ftell(fp)); //tells the cursor position as 5
printf("\n Enter the character to insert:");
scanf("\n%c",&ch);
fputc(ch,fp); //inserts the character at specified position
ch=fgetc(fp);
while(ch!=EOF) //prints all the characters from specified position
{
printf("%c",ch);
ch=fgetc(fp); The content of stud.txt
} pradKep is a good boy.
rewind(fp); //places the cursor to the beginning of file
printf("\n The cursor is at %d position",ftell(fp));
fclose(fp);
}
Output:
Enter the text into file (end with ctrl+d):
pradeep is a good boy.
18 Files
Program #7
Write a program to reverse the content of file.
#include<stdio.h>
main()
{
FILE *fp1,*fp2;
char ch;
fp1=fopen("sample.txt","w+");
if(fp1==NULL)
{
printf("\n Unable to open file:");
exit(0);
}
printf("\n Enter the text into file (end with ctrl+d):");
ch=getchar();
while(ch!=EOF)
{
fputc(ch,fp1);
ch=getchar();
}
fp2=fopen(“reverse.txt”,”w”);
fseek(fp1,0,2);
while(fseek(fp1,-2,1)= =0)
{
ch=fgetc(fp1);
putchar(ch);
fputc(ch,fp2);
}
fclose(fp1);
fclose(fp2);
}
Output:
Enter the text into file (end with ctrl+d):
Files topic is easy one.
.eno ysae si cipot seliF (content of reverse.txt)
Program #8
Write a program to print the transpose of matrix in a file
#include<stdio.h>
main()
{
FILE *fp;
int i,j;
int matrix[2][3]={{1,2,3},{4,5,6}};
fp=fopen(“mat”,’w”);
fprintf(fp,”\t Transpose matrix\n”);
for(i=0;i<2;i++)
{
for(j=0;j<3;j++)
fprintf(fp,”%d\t”,matrix[j][i]);
fprintf(fp,”\n”);
}
fclose(fp);
}
Output:Content of file “mat”
1 4
2 5
3 6
19 Files
Program #9
Write a program to demonstrate a random-access file
#include<stdio.h>
main()
{
struct student
{
int rno,rank;
char name[15];
float fees;
struct date_of_birth
{
int day,month,year;
}dob;
}s1;
FILE *fp;
char ch;
int sz,len,n,i;
fp=fopen(“sturecords”,”w”); //create a new file
if(fp==NULL)
{
printf(“\n Unable to open file”);
exit(0);
}
do
{
printf(“\nEnter student details (rno,name,rank,fees and date of birth):”);
scanf(“%d%s%d%f%d%d
%d”,&s1.rno,s1.name,&s1.rank,&s1.fees,&s1.dob.day,&s1.dob.month,&s1.dob.year); //read the student record
from keyboard
fwrite(&s1,sizeof(s1),1,fp); //write the student record to file
printf(“\n Do u want to add one more record (y/n):”);
scanf(“\n%c”,&ch);
}while(toupper(ch)!=’N’);
fclose(fp);
sz=sizeof(s1);
len=ftell(fp);
n=len/sz;
fp=fopen(“sturecords”,”r”); //open the file in read mode
if(fp==NULL)
{
printf(“\n Unable to open file”);
exit(0);
}
do
{
printf(“\n Enter the record number to read (o to stop):”);
scanf(“%d”,&i);
if(i>0 && i<=n)
{
fseek(fp,(i-1)*sz,SEEK_SET);
fread(&s1,sz,1,fp);
printf(”\n%d\t%s\t%d\t%f\t%d/%d/%d”,s2.rno,s2.name,s2.rank,s2.fees,s2.dob.day,
s2.dob.month,s2.dob.year);
}
}while(i);
fclose(fp);
}
20 Files
Output:
Enter student details (rno,name,rank,fees and date of birth):
1 master 1 27500.00 12 3 1990
Do you want to add one more record (y/n):y
Enter student details (rno,name,rank,fees and date of birth):
2 maya 13 23500.00 11 9 2004
Do you want to add one more record (y/n):y
Enter student details (rno,name,rank,fees and date of birth):
3 maneesha 14 22500.00 23 3 1982
Do you want to add one more record (y/n):n
Program #10
Write a program to merge multiple files into one file using command line arguments
#include<stdio.h>
main(int argc,char *argv[])
{
FILE *fp,*fp2;
int i;
fp2=fopen(“ans”,”a”);
for(i=1;i<argc;i++)
{
fp=fopen(argv[i],”r”);
while((ch=fgetc(fp))!=EOF)
fputc(ch,fp2);
}
fclose(fp);
fclose(fp2);
}
Output:
$./a.out stud.txt sample.txt master.txt
content of file ans
=========
pradeep is a good boy.
Mater minds are not made.
Master minds are born.
Master minds are not born. They are made.
But master minds are mad.
Master minds’ numbers consist of digits: 0-9
The persons who read this text are master minds
21 Files
Program #11
Write a program to search for particular word in a file
#include<stdio.h>
#include<string.h>
main()
{
FILE *fp;
char ch,temp[15],word[15],filename[15];
int count=0;
22 Files
Program #12
Write a program convert the text in file into upper case
#include<stdio.h>
main()
{
FILE *fp1,*fp2;
char ch;
fp1=fopen(“master.txt”,”r”);
fp2=fopen(“case.txt”,”w”);
ch=fgetc(fp1);
while(ch!=EOF)
{
fputc(toupper(ch),fp2);
ch=fgetc(fp1);
}
fclose(fp1);
fclose(fp2);
fp2=fopen(“case.txt”,”r”);
ch=fgetc(fp2);
while(ch!=EOF)
{
printf(“%c”,ch);
ch=fgetc(fp2);
}
fclose(fp2);
}
output:
content of master.txt
=======
Master minds are not born. They are made.
But master minds are mad.
Master minds’ numbers consist of digits: 0-9
The persons who read this text are master minds
content of case.txt
=========
MASTER MINDS ARE NOT BORN. THEY ARE MADE.
BUT MASTER MINDS ARE MAD.
MASTER MINDS’ NUMBERS CONSIST OF DIGITS: 0-9
THE PERSONS WHO READ THIS TEXT ARE MASTER MINDS
13.5. Error-handling
While processing files, we usually assume that:
o The file that is opened exists.
o There is enough space on the disk for the file.
o The functions fseek(), fread(), fwrite()…etc carry out the requested job successfully.
It is important to note that these assumptions are not always true. There is possibility of the following
errors in manipulating files:
23 Files
Error Reason
File not found Wrong file name used (spelling mistake, error in the path specified) or file actually
not present.
Disk full When writing to a disk with no more free sectors.
Disk write protected The disk has its write protect tag put on or some software has disabled writes to the
disk.
Unexpected EOF File length is zero of file length is less than that expected.
Sector not found (i) Reading and writing to two different streams, one as read only and the
other write only, but the file used for these streams is the same.
(ii) The disk head is not aligned on the physical sectors.
The error-handling functions in C are:
perror() function: The perror() function is used to print the nature of the error. It has the following
prototype:
The argument msg points to an optional user-defined message. This message is printed first, followed
by a colon and the implementation-defined message that describes the most recent error. If you call
perror() when no error has occurred, the message displayed is no error.
Program #13
Write a program to demonstrate perror() function
#include <stdio.h>
#include <stdlib.h>
main()
{
FILE *fp;
char filename[80];
24 Files
Interview question #7
What is the purpose ferror()?
The ferror() is a macro that tests the given file pointer for a read or write error. It has the following
prototype:
Program #14
Write a program to demonstrate ferror()
#include<stdio.h>
main()
{
char filename[15],ch;
FILE *fp;
printf("\n Enter file name:");
scanf("%s",filename);
fp=fopen(filename,"r");
if(fp==NULL)
{
printf(“\n Unable to open file”);
exit(0);
}
fputc(ch,fp);
if(ferror(fp)>0)
{
perror("error");
}
fclose(fp);
}
Output:
Enter file name: master.txt
error: Bad file descriptor.
25 Files
when we try to count the number of characters of a text file, each new line character contributes
by one.
2) The eof character: The eof character in text files corresponds to the character having ASCII code
26. In binary files, there is no such explicit eof character. The binary files do not store any special
character at the end of the file and their file-end is verified by using their size itself.
3) While discussing binary files, one more point is worth mentioning and corresponds to storage of
numbers in binary format. The numbers can be written to files using fprintf() statement as a
sequence of characters. E.g., the number 1001 can be written using fprintf() as a sequence of
characters: ‘1’,’0’,’0’,’1’. It means that storage of 4-digit number will take 4 bytes. But on a 16-bit
computer, an integer needs 2 bytes of storage and this concept can be utilized with help of fwrite()
statement. The fwrite() function will store every integer value by taking two bytes.
13.7. Conclusion
File is a collection of related data that is stored permanently on disk. There are two types of files namely
stream-oriented files and system-oriented files. In this chapter, we have studied only stream-oriented
files: text files and binary files. Based on the type of access, the stream-oriented files are broadly
classified as sequential-access files and random-access (or direct access) files.
26 Files