0% found this document useful (0 votes)
27 views10 pages

Bpops103 Module 5 Files Textbook

The document provides an overview of file handling in C programming, including the types of files (ASCII text and binary), file streams, and the necessary operations for reading and writing data. It explains the importance of using files for managing large amounts of data and introduces key concepts such as file pointers, opening files, and error handling. Additionally, it outlines the steps to declare, open, process, and close files in C, along with the various file modes available.

Uploaded by

yuvarajravi456
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views10 pages

Bpops103 Module 5 Files Textbook

The document provides an overview of file handling in C programming, including the types of files (ASCII text and binary), file streams, and the necessary operations for reading and writing data. It explains the importance of using files for managing large amounts of data and introduces key concepts such as file pointers, opening files, and error handling. Additionally, it outlines the steps to declare, open, process, and close files in C, along with the various file modes available.

Uploaded by

yuvarajravi456
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

16

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

In atext filc, an integer valuc 123 will be storcd as a File Name


auencc of'three characters-1,2, and 3. So cach character associated with it. The
Every file on the disk has a name operating
il take Ibyte and, therefore, to store the integer value naming convention of a file varies from one file name
i23 we necd 3 bytes. However, in a binary file, the int system to another. For example, in
DOS the
value 123 will be stored in 2 bytes in the binary form. This
clearly indicates that binary files take less space to store can have one to eight characters optionally followed by
to three characters.
a period and an extension that has one
e same piece of data and eliminate conversion between However, Windows and UNIX permit filenames having
internal and external representations and are thus more maximum of 256 characters. Windows also lays
some
efficicnt than the text filcs, restrictions on usage of certain characters in the filenames,
cannot be
i.e., characters such as /,\,:,*,?,",<,>, and !
part ofa file name.
information instead
InC, fopen() may contain the path
16.2 USING FILES IN C of specifying the filename. The path
information
gives
about the location of the file on the disk. If a filename
To use fles in C, we must follow the steps given below: that the file is
is specified without a path, it is assumed example, if a
declare a file pointer variable located in the current working directory. For directory
" open the
file file named student. DAT is located on Ddrive in
process the file BCA, then the path of the file can be specified by writing
close the file D:\BCA\Student.DAT
In this section, we will go through all these steps in detail. In C, a backslash character has a special meaning with
respect to escape sequences when placed in a string. So in
16.2.1 Declaring a File Pointer Variable order to represent a backslash character in a Cprogram,
you must precede it with another backslash. Hence, the
There can be a number of fileson the disk. In order to access above path will be specified as given below in the C
a particular file, you must specify the name ofthe file that has
program.
to be used. This is accomplished
Programming Tip: by using a file pointer variable D:\\BCA\\Student.DAT
An error will be that points to a structure FILE
generated if you (defined in stdio.h). The file File Mode
use the filename to pointer will then be used in all
access a file rather
subsequent operations in the The second argument in fopen() is the mode. Mode
than the file pointer. file. The syntax for declaring a conveys to Cthe type of processing that will be done with
file pointer is the file. The different modes in which a file can be opened
FILE *file_pointer_name; for processing are given in Table 16.1.
For example, if we write Look at the code given below which opens a file using
FILE *fp; fopen().

Then, fp is declared as a file pointer. FILE *fp;


fp = fopen("Student.DAT", "r");
if(fp==NULL)
16.2.2 Opening a File {
Afile must first be opened before data can be read from printf("\n The file could not be opened");
or written to it. In order to open a file and associate it with exit(1) ;
a stream, the fopen() function is used. The prototype of
fopen() can be given as OR
FILE *fopen(const char *ile_name, const char
*mode); char filename [30];
FILE *fp;
Using the above declaration, the file whose pathname gets (flename);
is the string pointed to by
file_name is opened in the fp = fopen (filename, "r+");
Programming Tip: if (fp==NULL)
Afile must be opened mode specified using the
before any operation mode. If successful, fopen()
can be performed returns pointer-to printf("\n The file could not be opened");
on it. structure and if it fails. it exit(1);
returns NUL L.
418 ComputerFundannentals and Programmingin C

Table 16.1 file modes opened simultancously, the


Programming Tip: programmer must close afile
Modc Descripion
It is always when it has been used. The
Open a text ile for reading. lf the stream (file) does recommended to
not exist, then an emor willbe reported. prototype of the fclose()
close all the opened function can be given as
Open a text file for writing. If the stream does not files when they are
CNINt, then it is created. If the file already exists, then int fclose(FILE *fp);
not going to be used
Here, fp Is a hle pointer
its contents would be deleted. further in the program.
Append to a text file. If the file does not exist. it is which points to the file that
createi, has to be closed. The function
returns an integer value which indicates whether fclose()
Open a binary file for reading. 'b indicates binary. was successful or not. A zero is returned if the function
Bv default this will be a sequential file in Media 4
fomat. was successful, and a non-zero value is returned if an error
Occurred.
wb Open a binary file for writing.
Append to a binarv tile.
Note
Open atet ile for both reading and writing.The
stream willbe positioned at the beginning of the file. When fclose() is executed, any unwritten buffered data
When you specity 'r+'. you indicate that you want for the stream will be written to the file and any unread
to read the tile before vouwrite to it. Thus, the file buffered data will be discarded.
must alrRadv exist.
Open a text file for both reading and writing. The
sream will be created if it does not exist, and will be In addition tofclose(), there is afunction fcloseall(0
truncatedif it exists. which closes all the streams that are currently opened
24
Open a text file for both reading and writing. The except the standard streams (such as stdin, stdout, and
stream will be positioned at the end of the file content. stderr). The prototype of fcloseall () can be given as
rtb/tb+ Open a binary fle for read/write. int fcloseall (void) ;
w+b/wb+ Create abinary file for read/write.
a+blab+ Append a binary file for read/write.
fcloseall()also flushes any stream buffers and returns
the number of streams closed.
Ifa file's buffer has to be flushed without closing it then
use fflush() or flushall() to flush the buffers of all open
We have already discussed that fopen() returns a pointer streams.
to FILE structure if successful and a NULL otherwise. So it is
recommended to check whether
Programming Tip: the file was successfully opened 16.3 READING DATA FROM FILES
An error will be before actually using the file.
generated if you try The fopen() function can fail Cprovides the following set of
to open a file that to open the specified file under a file.
functions to read data from
does not exist. certain conditions that are listed
as follows: fscanf()
Opening a file that is not ready for use fgets()
Opening afile that is specified to be on a non-existent fgetc()
directory/drive fread()
Opening a non-existent file for reading In this section, we will read about
these functions.
Openinga file to which access is not permitted
16.3.1 fscanf()
16.2.3 CIlosing a File Using fclose() The fscanf() function is used to read
To close an open file, the fclose() function is used which the stream. The syntax of formatted data from
fscanf() can be given as
disconnects a file pointer from a file. After fclose() has int fscanf(FILE *stream,
const char *format,...) ;
disconnected the file pointer from the file, the pointer can be The fscanf() function is used to
used to access a different file or the sanme file but in a different read data from the stream
mode. The fclose() function not only closes the file, but also and store them according to the
flushes all the bufers that are maintained for that file. locations pointed by the parameter format into the
If you do not close a file after using it, the system these additional argumentsadditional arguments. However,
must point to the objects that
closes it automatically when the program exits. However, have already occupied memory. These
since there is a limit on the number of files which can be as specified by their corresponding objects are of type
format string. format tag within the
Files 419

Sinilar to the format spccifiers used in scanf(), #include <stdio .h>


in fscanf() also the format specifiers is a C string that int main()
begins with a percentage sign(%). The format specifier is
Ised to specity the type and format of the data that has FILE *fp;
o be obtained from the stream and stored in the memory char name [80];
locations pointed by the additional arguments, The int roll no;
nrototypeof a fornat specifier can be given as fp = fopen ("Student.DAT", "r");
%[*][width] [modifiers]type, where if (fp==NULL)
{
printf("\n The file could not be
is an optional argument that suppresses assignment
of the input field. It indicates that data should be read opened") ;
trom the stream and ignored (not stored in the memory exit(1);
location).
printf("\n Enter the name and roll number
width specifies the maximum number of characters to be
read. However, fewer characters willbe read if the fscanf of the student: ");
1 READ FROM KEYBOARD
function encounters a white space or an unconvertible fscanf (stdin, "%s %d" , name, &roll_no);
character. /* read from keyboard */
modifiers can be h, 1, or L for the data pointed by the printf("\n NAME: %s \t ROLL NUMBER = %d",
corresponding additional arguments. Modifier h is used name, roll no);
for short int or unsigned short int, l is used for long 1/ READ FROM FILE Student.DAT
int, unsigned 1long int, or double values. Finally, L is fscanf(fp, "%s %d", name, &roll_no);
used for long double data values. printf("\n NAME: %s \t ROLL NUMBER = %d",
name, roll_no);
type specifies the type of data that has to be read. It also fclose(fp);
indicates how this data is expected to be read from the return 0;
user.
The type specifiers for fscanf function are given in
Table 16.2. Output
Enter the name and roll number of the student:
Table 16.2 Type specifiers 01 Zubin
Type Qualifying input NAME: Zubin ROLL NUMBER = 01
C for single characters NAME: Goransh ROLL NUMBER = 03
D for decimal values
e,E, f. g, G for floating point numbers
Note
for octal numbers
for a sequence of (string of) characters Ifyou want to use fprintf ) to write on the screen,
for unsigned decimal values then specify stdout instead of specifying any other file
x, X for hexadecimal values poln
The fscanf function has some additional arguments. 16.3.2 fgets()
Each of the additional arguments must point to an object The fgets() function stands for fileget string. The fgets()
of the type specified by its corresponding %tag within the
format string, in the same order.
function is used to get a string from a stream. The syntax of
fgets() can be given as
Note char *fgets (char *str, int size, FILE
The fscanf function is similar to the scanf function, *stream);
except that the first argument of fscanf specifies a The fgets () function reads at most one less than the
stream from which to read, whereas scanf can only read number of characters specified by size (gets size - 1
from standard input. characters) from the given stream and stores them in the
string str. The fgets () fuction terminates as soon as it
Let us look at an example which illustrates the use
of encounters either a newline character, EOF, or any other
fscanf(). Here, we will not give the complete program error. However, if a newline character is encountered it
use of is retained. When all the characters are read withoutany
but just a partial program to demonstrate the error, a '\0' character is appended to the end of the string.
fscanf ().
420 Computer Fundamentals and Programming in C

The gets() and fgets() functions are alnmost same


except that gets() has an intinite size and astreann of FILE *fp;
stdin. Another difference is that when gets () encounters char str[80];
a newline character, it does not retain it, ic.. the newline int i, ch;
character (if anv) is not stored in the string. fp = fopen("Program.C", "r");
On successtul conmpletion, fgets() will return str. if(fp==NULL)
However, if the stream is at EOF, the EOF indicator for the
strean will be sct and fgets () will retum a NULL pointer. printf("\n The fle could not be
In case, fgets() encounters any error while reading, the opened") ;
eTOr indicator for the stream will be set and NULL pointer exit(1) ;
will be retumed. Look at the program code given below
which demonstrates the use of fgets(). // Read 79 characterS and store them in str
#include <stdio.h> ch = fgetc (fp);
int main() for (i=0; (i < 79) && (feof (fp) == 0); i++)

FILE *fp; str[i] = (char)ch;


char str[80]; ch = fgetc(stream);
1/ reads character by character
fp = fopen("ABC.DAT", "r");
if (fp==NULL)
str[i] = '\0';
printf("\n The fle could not be opened"); 1/ append the string with a null character
exit (1) ; printf("\n %s", str);
fclose(fp);
/* the fle will read 79 characters during
each iteration and will print them on the
The above program displays either first 79 characters
SCreen */ or less characters if the file contains less than 79
while (fgets(str, 80, fp) != NULL) characters.
printf("\n %s", str); The feof()function is used to detect the end offile. We
printf("\n\n File Read. Now closing the file"); will read more on this function later in this chapter.
fclose(fp);
return 0; 16.3.4 fread()
The fread() function is used to read data from a file. Its
Output syntax can be given as
Abdceweeferrttet gfejjherroiew tjketjer int fread (void *str, size t size, size_t num,
fddfgdfgfd FILE *stream) ;
File Read. Now closing the file
The fread() function reads num number of objects
16.3.3 fgets() (where each object is size bytes) and places them into the
array pointed to by str. The data is read from the given
The fgetc() function returns the next character from input stream.
stream, EOF if the end of file is reached, or if there an
Upon successful completion, fread() returns the
error. The syntax of fgetc() can be given as number of bytes successfully read. The number of
int fgetc (FILE *stream) ; objects will be less than num if a read error or end-of-file
is encountered. If size or num is 0, fread() will return 0
fgetc()returns the character read as an int or returns EOF and the contents of str and the state of the stream remain
to indicate an error or end of file.
unchanged. In case of error, the error indicator for the
fgetc() reads a single character from the current stream will be set.
position of a file (file associated with stream). After The fread() function advances the file position
reading the character, the function increments the indicator for the stream by the number of bytes read.
associated file pointer (if defined) to point to the next
character. Howeve, if the stream has already reached the
end of file, the EOF indicator for the stream is set. Look at Note
the following program code which demonstrates the use of The fread()function does not distinguish between end
fgets() function.
of-file and error. The programmer must use feof and
#include <stdio.h> ferror to determine which of the two has occurred.
main()
Files 421

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.

Output 16.4.1 fprintf()


First 9 characters of the file are: Hello how The fprintf() function is used to write formatted output
Since fread() returns the number of bytes successfully tostream. The syntax of fprintf) can be given as
read, we can also modify the above program to print the int fprintf (FILE * stream, const char *
number of bytes read. This would be helpful to know how format, ...);
many characters were read.
The function writes data that is formatted as specified
#include <stdio.h>
by the format argument to the specified stream. After the
main() format parameter, the function can have as many additional
{ arguments as specified in the format.
FILE *fp; The parameter format in fprintf() is nothing but a
char str[80]; Cstring that contains the text that has to be written on
size_t bytes _read; to the stream. Although not mandatory, fprintf() can
fp = fopen("Letter. TXT", "r+"); optionally contain format tags that are replaced by the
if(fp==NULL) values specified in subsequent additional arguments and
are formatted as requested.
printf("\n The fle could not be opened");
exit(1); Note

There must be enough arguments for format because


bytes_read = fread(str, 1, 79, fp);
if there are not, then result will be completely
str[bytes_read+1]= '\0';
/* explicitly store null character at the unpredictable. However, if by mistake you specify more
end of str */
number of arguments, the excess arguments will simply
printf("\n First %d characters of the fle be ignored.
are: %s", bytes_read, str);
fclose(fp); The prototype of the format tag can be given as
}
The output will depend on the contents of the file. %[lags] [width][ -precision][length]specifier
Assuming 14 characters were read, the output can be given as Each fornmat specifier must begin with a %sign. The %
Hello how r u?
file
sign is followed by:
This program assumes that you have created a
Letter. TXT that contains 14 characters which have been flags which specifies output justification such as decimal
displayed above. point, numerical sign, trailing zeros, or octal or hexa
The fread() function does not check for overfiow in decimal prefixes. Table 16.3 shows the different types of
the receiving area of memory. It is the programmer's job flags with their description.
422 Computer Fundamentals and Programming in C
Table 16.3 lags in printf()
for(i 0;1 10; i+)
Flags Description
Let justify within the given data field width puts("\n Enter your name: "):
Displays the data with its numeric sign (either +or-) gets(name);
Used to provide adthitional specifiers such as o, x, X, 0, Fflush(stdin) ;
O.or 0X for octaland hexadecimalvalues, respectively. puts("\n Enter your salary: ");
for values except zero. Scanf("%E", 8salary);
The numhr is left-padded with zeos (0) instead of spaces. fprintf(fp, " (%d) NAME: [%-10.10s )
\t SALARY %5.2f", i, name, salary) :
wadrh spofes thc minimum number of characters to print
after being padded with zeros or blank spaces. fclose(fp);
prrcision speciies the maximum number of characters to
print. Output
Programming Tip:
" For integer spifiers (d. i, o, u, x, X): If youopen a file for Enter your name: Aryan
precision flag
specihes the minimum number of digits to be written. writing using wmode, Enter your salary: 50000
However, if the value to be writen is shorter than then the contents of Enter your name: Anshita
this number. the result is padded with leading zeros. file will be deleted. If Enter your salary: 65000
Otherwise, if the value is longer, it is not truncated. afile has to be used Enter your name: Saesha
" For character strings. precision specifies the maximum for reading as well as Enter your salary: 70000
number of characters to be printed. writting,it must be This example asks the user
opened in w+ mode to enter the name and salary
length fieldcan be explained as given in Table 16.4.
of 10 people. Each time the
speciñer is used to define the type and the interpretation of user enters the name and salary, the data read is written to
the value of the coTesponding argument. Details.TXT. The names are written on new lines in the
The fprintf() function may contain some additional file. In this example, we have used three format tags:
parameters as well depending on the format string. Each " %d to specify a signed decimal integer.
argument must contain a value to be inserted instead of " %-10.10s. Here indicates that the characters must be
each # tag specified in the format parameter, if any. In left aligned. There can be a minimum of 10characters as
other words. the number of arguments must be equal to the well as a maximum of 10 characters (.10) in the strings.
number of %tags that expect a value. " %f to specify a floating point number.
Table 16.4 Length field in printf()
Note
Length Description
When the argument is a short int or unsigned short If you want to use fprintf ()to write on the screen, then
int specify stdout instead of specifying any other file pointer.
1 When the argument is a long int or unsigned long
int for integer specifiers
L When the argument is a long double (used for
16.4.2 fputs()
loating point specifiers) The opposite of fgets () is fputs(). The fputs() function
is used to write a line to afile. The syntax of
fputs() can
Look at the program given below which demonstrates be given as
the use of fprintf(). int fputs (const char *str, FILE
#include <stdio.h>
*stream);
The fputs() function writes the string pointed to by
main()
str to the stream pointed to by stream. On successtul
FILE *fp;
completion, fputs () returns 0. In case of any eror,
int i;
fputs() returns EOF.
char name [20]; #include <stdio.h>
float salary; main()
fp = fopen ("Details. TXT", "w");
if(fp==NULL) FILE *fp;
{ char feedback[100];
printf("\n The file could not be opened"); fp = fopen("Comments.TXT", "w");
exit (1) ; if(fp==NULL)
File

When n output frett


print(\ The 4le could Not be openet'): Programming Tip i4 nbuffersd, informatien
evit(1): EOF san integer type appear on the destinatien
deftned in stdie. device a9
printf("\n Provide feadback on this book: ): and has a value 1 written When it i4 buffered
gets(feedbeck); character are saved nternally
4ush(stdin): and thenwritten out as agroup In order to force buffered
1/ feedback stored characters to he output before the buffer is full, use
fputs (feedback, fp): EAush()
fclose(fp):
16.4.4 fwr ite()
Output The Fur ite() function is used to write data to a file The
Provide feedback on this book: good eyntax of Fur ite can he given as
int furite(const void str. sIze t size,
16.4.3 fputc() slze t count, FtLE *stream) ;

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>

printf("\n The fle could not be int main (void)


opened");
exit (1); FILE *fp;
} size_t count;
printf("\n Provide feedback on this book: "); char str[] = "GO00 MORNING";
gets (feedback) ; fp = fopen("Welcome . txt", "wb");
for(i = 0;i < feedback[i];i++) if(fp==NULL)
fputc(feedback[i], fp); {
fclose(fp); printf("\n The fle could not be opened");
} exit(1);
Output
Provide feedback on this book: good count = fwrite(str, 1, strlen(str), fp);
printf("\n %d bytes were
Note
Written to the file", count);
fclose(fp);
Thestandard file stdout is buffered in case the output return 0;
unit is not the terminal. On the contrary, the standard
file stderr is usually unbuffered. However, the
settings of stdout and stderr can be changed using Output
setbuf. 13 bytes were written to the fle
424
Computer Fundamentals and Programming in C
Note printf("\n The file could not be opened"):
exit (1);
fwrite() can be used to write characters, integers, or
structures to a file. However, fwrite() can be used only /* The l0op continues until fp reaches
with files that are opened in binary mode. the end-of-fle */
while(! feof (fp))
16.5 DETECTING THE END-OF-FILE fgets(str, 79, fp);
// Reads 79 bytes at a time
When reading orwriting data to files, we often do not know printf("\n %s", str);
exactly how long the tile is. For example, while reading
the file, we usually start rcading from the beginning and printf("\n\n File Read. Now closing the
procced towards the end of the file. In C, there are two fle");
ways to detect EoF: fclose(fp);
" While reading the file in text mode, character by return 0;
character, the programmer can compare the character
that has been read with EOF, which is a symbolic constant
defined in stdio.h with a value -1. The following Output
statement does that 1 Aditya 2 Chaitanya 3 Goransh

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

You might also like