Writing to Files

Now that you know how to read data from a file, you might be wondering how to write data to a file. Writing to files is very similar to printing to standard output, we'll just quickly go through the functions you need to know about, and then you'll have a quick exercise before we move to more exciting topics.

Opening a file for writing

The same fopen function that you used for opening files for reading is also used to open the file for writing. Instead of "r", pass "w" or "a": use "w" if you want to overwrite the existing file, and "a" if you want to append to the end of the existing file. Both "w" and "a" will create the file if it does not exist.

FILE *f;

f = fopen("output.txt", "w");
if (!f) {
  perror("fopen");
}

Closing the file

Files opened for writing must be closed. If you don't close your file with fclose, chances are high that not all the data–or none of the data–will be actually saved to the file. The reason for that is that the file functions in C write data in chunks, which is more effective; fclose(f) forces the last piece of data to be actually dumped to the file. A special function fflush(f) dumps the pending data to the file immediately, without closing it; it's useful when your code keeps appending data to the file and you want this data to be completely written without closing the file.

Standard output is stdout

Similar to how stdin is a special file for standard input, variable stdout is a FILE * variable that is associated with the standard output. Any function listed below that writes to a file can be called with stdout (instead of f) and will write to standard output.

Functions to write to a file

The most basic function to write a string to a file is fputc, which is similar to putchar but for a file:

int c; /* int, to match fgetc and getchar. remember EOF? */
FILE *f;

fputc(c, f);

Actually, fputc(c, stdout) does the same as putchar(c).

To write a string to a file, you can use fputs:

char s[100];
FILE *f;

fputs(s, f); /* writes string s to file f */

I haven't mentioned this before, but there's also a function puts(s) which prints a string to standard output; puts(s) is equivalent to fputs(s, stdout).

If you need formatted output–similar to printf–use fprintf:

int a, b;
FILE *f;

fprintf(f, "values: %d and %d\n", a, b);

Note that while fputc and fputs accept the file as their last parameter, fprintf takes the file as the first parameter.

Given that you know how to print to standard output, writing to a file should not seem too difficult. Let's try!

In this small exercise, read all the content of input.txt and write it to output.txt.

#include <stdio.h>

int main() {
	/* TODO: open input.txt for reading and output.txt for writing;
     keep reading from input.txt and writing to output.txt.
     You can use fgets / fputs or fgetc / fputc.
   */

	return 0;
}

Now that we have learned the boring things, we can go back to exciting stuff! Stay tuned.

© Alexander Fenster (contact)