Bpops103 Module 5 Files Textbook
Bpops103 Module 5 Files Textbook
Files
TAKEAWAYS
" Streams in C " Error handling " Renaming files
" Reading data from files " Command line " Creating temporary files
" Writing data to files
arguments
" Random access of data
16.1 NTRODUCTION TO FILES keyboard, etc. Although files may differ in the form and
capabilities, all streams are the same.
The three standard
A fleis acollection of data stored on a secondary storage KEYBOARD
device like hard disk. Till now, we had been processing streams (Figure 16.1) in C
data that was entered through the computer's keyboard. language are as follows: stdin
But this task can become very tedious especially when standard input PROGRAM
there is a huge amount of data to be processed. A better (stdin)
solution., therefore, is to combine all the input data into a standard output stdout stderr
file and then designa C program to read this data from the (stdout) SCREEN
file whenever required. standard error
Broadly speaking, a file is basically used because real (stderr) Figure 16.1 Standard streams
life applications involve large amounts of data and in such
applications the console-oriented I/O operations pose two Standard input (stdin) Standard input or the strean from
major problems: which the program receives its data. The program requests
First, becomes cumbersome and time-consuming to
transfer of data using the read operation. However, not all
handle huge amount of data through terminals. programs require input. Generally, unless redirected, input
Second, when doing I/O using terminal, the entire data is
for a program is expected from the keyboard.
lost when either the progranm is terminated or computer is Standard output (stdout) Standard output is the stream
turned off. Therefore, it becomes necessary to store data where a program writes its output data. The program
on a permanent storage device (e.g. hard disks) and read requests data transfer using the write operation. However,
whenever required, without destroying the data. not all programs generate output.
In order to use files, we have to learn file input and Standard error (stderr) Standard error is basically an
output operations, i.e., how data is read from or written output stream used by programs to report error messages
to a file. Although file I/O operations are almost same as or diagnostics. It is a stream independent of standard
terminal VO, the only difference is that when doing file output and can be redirected separately. No doubt, the
VO, the user must specify the name of the file from which standard output and standard error can also be directed to
data should be read/written. the same destination.
A stream is linked to a file using an open operation and
16.1.1 Streams in C dissociated from a file using a close operation.
In C, the standard streams are termed as pre-connected 16.1.2 Buffer Associated with File Streams
input and output channels between a text terminal and the
program (when it begins execution). Therefore, stream is When a stream linked to a disk file is created, a buffer
a logical interface to the devices that are connected to the is automatically created and associated with the stream.
computer. A buffer is nothing but a block of memory that is used
Stream is widely used as a logical interface to a file for temporary storage of data that has to be read from or
where a file can refer to a disk file, the computer screen, written to a file.
416 Computer Fundamentals and Programming in C
Buffers are needed because disk drives are block
oriented devices as theycan operate efficiently when data Programming Tip: Another important
that when atext thing is
has to be read/written in blocks of certain size. An The contents of a
are
file is used, there
buffer size is ideal binary file are not actually two representations
hardvware-dependent.
The buffer acts as an interface between the human-readable. If
of
Fordata--internal
or extemal
stream
(which is character-oriented) and the disk hardware (which youwant the data example, an int value
will be represented as 2 or 4
is block-oriented). When the stored in the file to
program has to write data to
the stream, it is saved in the buffer be human-readable, bytes of memory internally.
till it is but externally the int
entire contents of the buffer are written to full. Then the then store the data in value
the disk as a will be
block. This is shown in Figure 16.2. atext file.
of represented as a string
characters
decimal representingvalue.its
or hexadecimal
Data from the
Program To convert internal representation into external, we can
buffer is
writes data use printf and fprintf functions.
an external representation into internalSimilarly, to Convert
written to the
PROGRAM to buffer
R BUFFER s
disk file scanf andfscant
DISK can be used. We will read more about these
functions in the
Figure 16.2 Buffers associated with coming sections.
streams
Note
Similarly, when reading data from a disk file, the data
is read as a block from the file In atext file, each line of data ends with a newline
and
The program reads data from the written into the buffer. character. Each file ends with a special character called
buffer. The creation and
operation of the buffer is automatically the end-of-file (EOF) marker.
operating system. However, C provides handled some
by the
for buffer manipulation. The functions
until the buffer is flushed or data resides in the buffer Binary Files
written to a file.
A binary file may contain any type
of
16.1.3 Types of Files binary form for computer storage and data, encoded in
In C, the types of files used can be Like a text file, a binary file is a processing purposes.
collection of bytes. In C, a
two categoriesASCII text files andbroadly classified into byte and a character are
equivalent. Therefore, a binary file
binary files. is also referred to as a
character
two essential differences: stream with the following
ASCII Text Files
" Abinary file does not
A text file isa stream of
characters that can be sequentially the data and each byterequire any special processing of
of data is transferred
processed by a computer in forward direction. the disk unprocessed. to or from
For this
reason, a text file is usually opened for only one kind of Cplaces no
operation (reading, writing, or appending) at any given restrictions on the file, and it may be read
from, or written
time. Because text files only to, in any manner the
process
only read or write data one character atcharacters, they can wants. programmer
a timne. In C, a text While text files can be
stream is treated as a special kind of file. processed sequentially, binary
Depending on the requirements of the operating system files, on theother hand, can be either processed
or randomly on the needs of the sequentialyIn
C, to processdepending
and the operation that has to be performed (read/write
operation) on the file, newline characters a file randomly, the application.
to or from carriage return/line feed may be converted the current file position to an programmer must move
this, other character combinations. Besides before reading or writing data.appropriate
For
place in the file
conversions may
satisfy the storage requirements of the also be done to used to store records (using example, if a file is
However, these conversions occur operating system. to update a structures) of students, then
particular record, the programmer must hrst
a text file. transparently process
to locate the appropriate record,
In a text file, each line
contains zero or more characters
update it, and finally write theread the record into memory
record back to the disk
and ends with one or more appropriate location in the file. at its
characters that specify the end
of line. Each line in a text file can have a maximum of 255
characters. A line in a text file is not a Cstring, so it is not
Note
terminated by a null character. When data is written to a Binary files store data in the
text file. each newline character is internal representation
converted to a carriage
return/line feed character. Similarly, when data is read format. Therefore, an int value
from atext file, each carriage return/line feed form as a2 or 4 byte value. The will be stored in binary
character is to store data in same format is used
converted into newline character. memory as well as in file. Like text
binary file also ends with an EOF hie,
marker.
Files 417
Look at the program given below whichillustrates the toensure that the memory pointed to by str must be larze
usc of fread(). enough to hold the number of objects being read.
#include <stdio.h> If you have opened a stream for updating and later
main() you want to switch from reading to writing or vice versa,
you must first use the fseek() or rewind) function.
FILE *fp; However. if you have been reading and have reached
char str[11]; end-of-file, then youcan immediately switch to writing.
fp = fopen("Letter. TXT", "r"): We will discuss the fseek() and rewind functions later
if(fp==NULL) in this chapter.
printf("\n The ile could not be opened"); 16.4 WRITING DATA TO FILES
exit(1) ;
provides the following set of functions to read data from
C
fread(str, 1, 10, fp); a file:
* In the str 10 objects of 1 byte are read
from the file pointd by fp */ " fprintf()
str[10]= '\0; fputs()
printf("\n First 9 characters of the fle fputc()
are: %s", str); fwrite()
fclose(fp); In this section, we will read about these functions.
The fputc() function is just the opposite of fgetc() and The fwrite() function will write objects (number
Is used to wnte a character to the stream. of objects will be specified by count) of size specified
stream
int fputc (int c, FILE *Stream) ; by size, from the array pointed to by str to the
pointed to by stre am.
The fputc 0function will write the byte specified by The file-position indicator for the stream (if defined)
C(oonvertd to an unsigned char) to the output stream will be advanced by the number of bytes successfully
ointed to by stream On successful completion,fputc() written. If an error occurs, the resulting value of the file
ullretum the value it has written. Otherwise, in case of position indicator for the stream is unspecified.
crnor, the function will retun EOF and the error indicator On successful completion, the fwrite() function
for the stream willbe set. returns the number of objects successfully written. The
#include <stdio.h> number of objects will be less than count if an error is
main() encountered. If size or count is 0, fwrite() will return
0and the contents of the stream remains unchanged.
FILE fp; In case of error, the error indicator for the stream will
char feedback [100]; be set.
int i;
#include <stdio.h>
fp = fopen ("Comments. TXT", "w");
#include <string.h>
if(fp==NULL) #include <stdlib.h>
while(1)
C= fgetc(fp);
1/ here c is an int variable
16.6 ERROR HANDLING DURING FILE
if (C==EOF)
OPERATIONS
break;
printf("%c", c) ; It is quite common that an error may occur while reading
data from or writing data to a file. For example, an error
may arise
" The other way is to use the standard library function
when trying to read a file beyond EOF indicator
feof() which is defined in stdio.h. The feofO
function is used to distinguish between two cases: when trying to read a file that does not exist
" when trying to use a file that has not been opened
When a stream operation has reached the end of afile " when trying to use a file in an inappropriate mode, i.e.,
" When the EOF error code has returned an error writing data to a file that has been opened for reading
indicator even when the end of the file has not been
" when writing to a file that is write-protected (i.e., trying
reached to write to a read-only file)
If we fail to check for errors, then the program may
The prototype of feof() can be given as behave abnormally. Therefore,
int feof(FILE *fp); Programming Tip: an unchecked error may result
An error will be in premature termination of the
The function takes a pointer to the FILE Structure of
the stream to check as an argument and returns zero
generated if you try program or incorrect output.
to read a file that is In C, the library function
(false) when the end of file has not been reached and a opened in wmode ferror() is used to check
one (true) if the end of file has been reached. Look at the and vice versa. for errors in the stream. Its
following: prototype can be given as
The output assumes that a file Student. DAT already
exists and conatins the following data: 1 Aditya 2 int ferror (FILE *Stream);
Chaitanya 3 Goransh
The ferror() function checks for any errors in the
#include <stdio.h> stream. It returns value zero if no errors have occurred and
main() a non-zero value if there is an error. The error indication
will last until the file is closed or it is cleared by the
FILE *fp; clearerr() function. Look at the code given below which
char str [80]; uses the ferror().
fp = fopen("Student. DAT", "r") ;
#include <stdio.h>
if(fp==NULL) main()