5.9.2.4. Stdio: Reading from a File

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


Testing for end of file

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.

fclose(f);

When you are done reading the file, close it. 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.

feof(f)

This is true if open file f is at the end of file. 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.

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