33C. Reading Files

To use the things described here, #include the <cstdio> library.

Opening a file for reading

Use
  FILE* f = fopen(path, "r");
to open file path for reading.

If it is not possible to open the file, fopen will return NULL. The standards for this course require programs to check for that and, if the file could not be opened, to report it, with the name of the file that could not be opened.


fclose(f);

When you are done reading the file, close it. The standards require you to do that. Parameter f has type FILE*.

fscanf(f, format, ...)

This works just like scanf, but it reads from open file f, which must have type FILE*.

getc(f)

This expression reads one character from open file f. It is like getchar, but reads from an open file.

Never store the result of getc into a variable of type char, because getc can return EOF, which is not a character.


feof(f)

This is true if an attempt has been made to read past the end of open file f.

Be careful about this. There is normally an end-of-line character at the end of a text file. If your program has not read that end-of-line character, the file is not at its end.

Even if there are no characters left in the file, feof can return false. It only returns true if there has been an attempt to read past the end of the file. You test feof(f) after reading something.



Exercises

  1. Write a complete program that takes two file names A and B from the command line. It should create a file called B and copy the entire contents of file A into file B. For example, if the executable program created from your C++ program is called copy, then command

      copy myfile.txt myfile.cpy
    
    makes a copy of myfile.txt that is called myfile.cpy. Answer