Reading and Writing Files 151
1. The starting address of an array of characters to store the data.
2. The number of characters to read.
3. A FILE * to read from.
If the second argument is n, the function reads as many as n - 1 characters from the
file. The function then adds the ending character, ’\0’, automatically. The function may
read fewer characters if (i) a new line character occurs before reading n - 1 characters
or (ii) the file has reached its end. Please note that fgets does not stop when it reads a
space. It can read multiple words in the same line even though these words are separated
by one or more spaces. For fscanf(...’’%s’’ ...), the size between % and s is optional.
For fgets, the size is a required argument. If fgets succeeds in reading anything from the
file, it returns the value of the first argument, i.e., the starting address to store the data. If
fgets fails to read anything from the file, it returns NULL.
The following program reads a file line by line and counts the number of lines. We assume
that the maximum length of each line is 80 characters, i.e., at least one ’\n’ occurs within
every 80 characters.
// fgets .c1
#in clude < stdio .h >2
#in clude < string .h >3
#in clude < stdlib .h >4
#d ef in e MAX _LINE _ LENGT H 815
// assume that the maximum length of each line is a l ready know6
int main ( i n t argc , char * argv [])7
{8
FILE * fptr ;9
int numLine = 0; // must initializ e to zero10
char oneLine [ MAX_ LINE_L ENGTH ];11
i f ( argc < 2)12
// must check argc before using argv [1]13
{14
printf (" Need to provide the file ’s name .\ n") ;15
return EXIT _FAILUR E ;16
}17
fptr = fopen ( argv [1] , " r") ;18
i f ( fptr == NULL )19
{20
printf (" fopen fail .\ n") ;21
// do not call fclose ( fptr ) here22
return EXIT _FAILUR E ;23
}24
printf (" The name of the file is %s .\ n ", argv [1]) ;25
while ( fgets ( oneLine , MAX_LINE_LENGTH , fptr ) != NULL )26
{27
numLine ++;28
}29
fclose ( fptr );30
printf (" The file has %d lines .\ n" , numLine );31
return EXIT _SUCCES S ;32
}33