33B. Writing Files


Writing to a file

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

Opening a file for writing

Use
  FILE* f = fopen(path, "w");
to open file path for writing. (Parameter path is a null-terminated string.) If that file already exists then it is emptied.

If it is not possible to open the file, fopen will return NULL.


Opening a file for appending

Use
  FILE* f = fopen(path, "a");
to open the given file (path), but without emptying the file if it already exists. Instead, append to the end of what is already in the file.

fclose(f);

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

fprintf(f, format, ...)

fprintf is similar to printf, but it writes to an open file. Parameter f has type FILE*, and must be a file that is open for writing.

putc(c, f)

Write character c into file f. This is much more efficient than printf for writing a single character.


Exercises

  1. Write a complete program that opens file "robinhood.txt", writes "Robin hood and his merry men" into the file, and closes the file. If the attempt to open the file fails, the program should write a message to the standard output saying so. Answer

  2. Redo the preceding problem, but instead of writing to file robinhood.txt, use the first command-line argument after the command as the file name.

    If there is no such command-line argument, write a message to the standard argument indicating that there should be one. Do not try to open the file.

    Answer