C provides the following set of functions to read data from a file. • fscanf(),• fgets(),• fgetc (),• fread().In this section, we will read about these functions.
READ
DATA FROM FILES
C
provides the following set of functions to read data from a file.
•
fscanf()
•
fgets()
•
fgetc ()
• fread()
In
this section, we will read about these functions.
The
fscanf() is used to read formatted data from the stream. The syntax of the
fscanf() can be given
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 locations pointed by the additional arguments.
However, these additional arguments must point to the objects that have already
occupied memory. These objects are of type as specified by their corresponding
format tag within the format string.
Similar
to the format specifiers used in scanf(), in fscanf() also the format
specifiers is a c string that begins with an initial percentage sign (%). The
format specifier is used to specify the type and format of the data that has to
be obtained from the stream and stored in the memory locations pointed by the
additional arguments. The prototype of a format specifier can be given as
[=% [*] [width] [modifiers] type=],
where
'*'
is an optional argument that suppresses assignment of the input field. It
indicates that data should be read from the stream and ignored (not stored in
the memory location).
width specifies
the maximum number of characters to be read. However, fewer characters will be
read if the fscanf function encounters a white space or an unconvertible
character.
modifiers
can be h, 1, or L for the data pointed by the corresponding additional
arguments. Modifier h is used for short int or unsigned short int, 1 is used
for long int, unsigned long int, or double values. Finally, L is used for long
double data values.
type
specifies the type of data that has to be read. It also indicates how this data
is expected to be read from the user.
The
type specifiers for fscanf function are given in Table 9.2.
The
fscanf function has some additional arguments. Each of the additional arguments
must point to an object of the type specified by its corresponding tag within
the format string, in the same order.
Note
The
fscanf function is similar to the scanf function, except that the first
argument of £scanf specifies a stream from which to read, whereas scanf can
only read from standard input.
Let
us look at an example which illustrates the use of fscanf (). Here, we will not
give the complete program but just a partial program to demonstrate the use of
fscanf().
#include <stdio.h>
main()
{
FILE *fp;
char name [80];
int roll_no;
fp = fopen("Student.DAT",
"r");
if (fp==NULL)
{
printf("\n The file could not
be opened");
exit (1);
printf("\n Enter the name and
roll number of the student: ");
// READ FROM KEYBOARD
fscanf (stdin, "%s %d",
name, &roll_no);
/* read from keyboard */
printf("\n NAME: %s \t ROLL
NUMBER = %d", name, roll_no);
// READ FROM FILE Student.DAT
fscanf(fp, = "%s %d", name, &roll_no);
printf("\n NAME: %s \t ROLL
NUMBER = %d", name, roll_no);
fclose(fp);
return 0;
}
}
Output
Enter
the name and roll number of the student: 01 Zubin
NAME:
Zubin ROLL NUMBER = 01
NAME:
Goransh ROLL NUMBER = 03
Note
If
you want to use fprintf () to write on the screen, then specify stdout instead
of specifying any other file pointer.
The
function fgets() stands for file get string. The fgets() function is used to
get a string from a stream. The syntax of fgets() can be given as
char *fgets (char *str, int size,
FILE *stream);
The
fgets() function reads at most one less than the number of characters specified
by size (gets size - 1 characters) 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. However, if a newline character is
encountered it is retained. When all the characters are read without any error,
a '\0' character is appended to the end of the string.
The
gets () and fgets() functions are almost same except that gets () has an
infinite size and a stream of stdin. Another difference is that when gets()
encounters a newline character, it does not retain it, i.e., the newline
character (if any) is not stored in the string.
On
successful completion, fgets() will return str. However, if the stream is at
EOF, the EOF indicator for the stream will be set and fgets() will return a
null pointer. In case, fgets() encounters any error while reading, the error
indicator for the stream will be set and null pointer will be returned. Look at
the program code given below which demonstrates the use of fgets().
#include <stdio.h>
main ()
{
FILE *fp;
char str[80];
fp = fopen("ABC.DAT",
"r");
if (fp==NULL)
{
printf("\n The file could not
be opened");
exit(1);
}
/* the file will read 79 characters
during each iteration and prints
them on the screen */
while (fgets (str, 80, fp) != NULL)
printf("\n %s", str);
printf("\n\n File Read. Now
closing the file");
fclose(fp);
return 0;
}
Output
Abdceweeferrttet gfejjherroiew
tjketjer
fddfgdfgfd
File Read. Now closing the file
The
fgetc() function returns the next character from stream, EOF if the end of file
is reached, or if there is an error. The syntax of fgetc () can be given as
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 (file associated
with stream). After reading the character, the function increments the
associated file pointer (if defined) to point to the next character. However,
if the stream has already reached the end of file, the EOF indicator for the
stream is set. Look at the following program code which demonstrates the use of
fgets() function.
#include <stdio.h>
main()
{
FILE *fp;
char str[80];
int i, ch;
fp = fopen("Program. C",
"r");
if (fp = =NULL)
{
printf("\n The file could not
be opened");
exit(1);
}
// Read 79 characters and store
them in str
ch= fgetc (fp);
for (i=0; (i < 79) &&
(feof (fp) = = 0); i++)
{
str[i] = (char) ch;
ch = fgetc (stream);
// reads character by character
}
str[i] = '\0';
// append the string with a null
character
printf("\n %s", str);
}
fclose(fp);
}
Output
#include <stdio.h>
main().....
displays either first 79 characters
or less characters if the file contains less than
79 characters
The
feof() is used to detect the end of
file. We will read more on this function later in this chapter.
The
fread() function is used to read data from a file. Its syntax can be given as
int fread(void *str, size_t size,
size_t num, FILE *stream);
The
function fread() reads num number of objects (where each object is size bytes)
and places them into the array pointed to by str. The data is read from the
given input stream.
Upon
successful completion, fread() returns the number of bytes successfully read.
The number of 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 and the contents of str
and the state of the stream remain unchanged. In case of error, the error
indicator for the stream will be set.
The
fread() function advances the file position indicator for the stream by the
number of bytes read.
Note
The
fread() function does not distinguish between end-of-file and error. The programmer
must use feof and ferror to determine which of the two has occurred.
Look
at the program given below which illustrates the use of fread().
#include <stdio.h>
main ()
{
FILE *fp;
char str[11];
fp = fopen("Letter.TXT",
"r+");
if (fp==NULL)
{
printf("\n The file could not
be opened");
exit(1);
}
fread (str, 1, 10, fp);
/* In the str 10 objects of byte
are read from the file pointd by fp */
str [10]='\0';
printf("\n First 9 characters
of the file are: %s", str);
fclose(fp);
}
Output
First 9 characters of the file are:
Hello how
Since
fread() returns the number of bytes successfully read, we can also modify the
above program to print the number of bytes read. This would be helpful to know
how many characters were read.
#include <stdio.h>
main ()
{
FILE *fp;
char str[80];
size_t bytes_read;
fp = fopen("Letter.TXT",
"r+");
if (fp==NULL)
printf("\n The file could not
be opened");
exit(1);
}
bytes_read = fread (str, 1, 79,
fp);
str [bytes_read+1]='\0';
// explicitly store null character
at the maths end of str
printf("\n First %d characters
of the file are: %s", bytes_read, str);
fclose(fp);
}
Output
Output will depend on the contents
of the file. Assuming 14 characters were read, the output can be given as Hello
how r u?
This program assumes that you have
created a file Letter.TXT that conatins 14 characters which has been displayed
above
The
function fread() does not check for overflow in the receiving area of memory.
It is the programmer's job to ensure that the memory pointed to by 'str' must
be large enough to hold the number of objects being read.
If
you have opened a stream for updating and later you want to switch from reading
to writing or vice versa, you must first use the fseek () or rewind ()
function. However, if you have been reading and have reached end-of-file, then
you can immediately switch to writing. We will discuss the fseek() and rewind
functions later in this chapter.
Programming in C: Unit V: File processing : Tag: : Syntax with Example C Programs - Read Data From Files
Programming in C
CS3251 2nd Semester CSE Dept 2021 | Regulation | 2nd Semester CSE Dept 2021 Regulation