next up previous contents index
Next: Subroutines, functions, and libraries Up: Input/Output Previous: Command line arguments   Contents   Index


File Handles

As with Perl, reading and writing to files is done through associating a physical file with a file handle. A file handle is declared as a FILE type:
FILE *fh;
(the meaning of the * will be explained when we discuss pointers), and then associated with a file through the use of fopen:
  FILE *fh;
  fh = fopen("data.txt", "r");
  if (fh == NULL) {
    printf("Could not open data.txt\n");
    exit (1);
  }
where, in this example, fh is the filehandle associated to data.txt. The second argument to fopen denotes the mode of how the file is to be opened:

For binary files, such as images, on Win32 generally you should add a b mode specifier (eg, wb).

After opening, it is generally good practice to check the file handle against NULL - if this is true, then opening the file failed for one reason or another, and you should act accordingly.

After opening a file, you can print to it (if opened in write or append mode) by use of the fprintf function:

 count = 22;
 fprintf(fh, "The counter is now %d\n", count);
which acts in exactly the same way as the printf statement, except the first argument specifies the file handle to write to. For reading from the file, the fscanf function can be used:
  while (! feof(fh) ) {
    fscanf(fh, "%d %s", &age, name);
    printf("%s is %d years old", name, age);
  }
which works in exactly the same way as scanf for getting input from standard input. Here, the data file is expected to be a series of lines of the form
33 Harry
22 Sally
102 George
and the while loop will read in a line, one at a time, until a special marker denoting the end of the file is reached (accessed through the feof call).
next up previous contents index
Next: Subroutines, functions, and libraries Up: Input/Output Previous: Command line arguments   Contents   Index