Reading from Files

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 Endings

One 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 , which terminates every string. Also note that fgets() will retain any newline characters it reads in. So if fgets() encounters a newline character, that will terminate the read, but that newline will be part of the value of var.

Our next example will open the weather.txt file and print out its contents line by line, exactly as they were stored. Much of this example's code will be similar to the previous two applications.

To read from files

1.
Create a new file or project in your text editor or IDE.

2.
Type the standard beginning lines of code (Script 12.3):

/* read_weather.c - Script 12.3 */
#include <stdio.h>

Script 12.3. The record_weather application retrieves and prints the contents of the weather.txt file.


3.
Set the file path and name as a C preprocessor macro:

#define THEFILE
 "/Users/larry/Desktop/weather.txt"

or

#define THEFILE "C:\Documents and
 Settings\Larry Ullman\Desktop\
 weather.txt"

Adjust this line accordingly, making sure only that it points to the same weather.txt file used by the record_weather application (Script 12.2).

4.
Begin the main function and create a file pointer:

int main (void) {
FILE *fp;

5.
Define the required variable:

char line[30];

Only one variable is necessary for this application (aside from the pointer). The line character array will store the data retrieved from the text file. Its length (30) allows for a reasonable amount of data, based on what we expect the text file to contain.

6.
Open the file for reading:

fp = fopen(THEFILE, "r");

The r mode is used to only read from a file.

7.
Start a conditional based on the file pointer and print a caption:

if (fp != NULL) {
    printf("The contents of the
 'weather.txt' file:
");

8.
Read and print the file's contents in a loop:

while (fgets(line, sizeof(line), fp))
{
    printf("%s", line);
}

This loop will continue to use the fgets() function to read in from the file as long as it can (which is until it reaches the file's end). With each iteration of the loop, the data read with fgets() is assigned to the line variable, which is then printed as a simple string.

9.
Complete the fp conditional:

} else {
    printf ("The file could not
 be opened.
");
    return 1;
}

10.
Close the file:

if (fclose(fp) != 0) {
    printf ("The file could not
 be closed.
");
}

11.
Complete the main function:

    getchar();
    return 0;
}

12.
Save the file as read_weather.c, compile, and debug as necessary.

13.
Run the application (Figure 12.8).

Figure 12.8. The application prints the contents of the weather.txt file, along with a caption.


✓ Tips

  • The feof() function takes a file pointer as an argument and returns 1 if you've reached the end of a file; it returns 0 otherwise.

  • C also has a fgetc() function, which will read in a single character at a time from a file:

    character = fgetc (fp);
    
  • The fscanf() function can be used to read from files as well, but can easily choke on formatting problems in the text file. Its syntax is like scanf():

    fscanf(fp, format, &var…);
    

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset