To read from a file in C, you can use the fgets() function. It was first introduced in Chapter 5 as a reliable way to read numeric input from the keyboard. The syntax for using fgets() is
fgets (var, length, pointer);
The function reads up to length amount of data from the file and assigns this to var. You should take precautions to ensure that the function does not attempt to read in more data than can be stored in the variable. A reliable way to do this is to use the sizeof() operator:
fgets (var, sizeof(var), pointer);
Line and File EndingsOne of the nice things about C with respect to working with files is that it will automatically convert line endings. Different operating systems use different characters to mark the end of a line. On Windows, a combination of a carriage-return ( ) and the newline or linefeed ( ) characters is used, resulting in . Pre–Mac OS X Macs used , while Unix uses . In C, you can just use , and that will be interpreted appropriately for the operating system in use. These line-ending characters only apply to text files, since binary files contain one long stretch of data. Another concept to consider is the end of file, referred to as EOF. Each operating system also uses its own way of marking the end of a file. When a C application reads in EOF, it knows there's no more data to be read. This EOF constant is also defined within the stdio.h header file so that it's environment specific. |
Finally, there is the pointer value. Previously the pointer being used was stdin (standard input), but now the pointer should refer to the file opened for reading:
fgets (var, sizeof(var), fp);
As a clarification, we stated that fgets() reads up to length amount of data. Technically the fgets() function will read from a file until any of the following conditions are met:
A newline ( ) is encountered.
The end of the file is reached (see the sidebar).
It has read one character less than the maximum number of characters to read.
Since fgets() reads in a string, it will read up to length - 1 characters. These will be assigned to the string, along with a final