Skip to content
Tutorials Center
My learning

Topics

Lesson 70 of 135 ยท File Input and Output

File Handling Basics

Learn file handling in C: FILE pointers, fopen modes (r, w, a, +, b, x), error checks with perror, fclose, fflush, and stdin, stdout and stderr.

Everything a program keeps in variables disappears when it ends. To save a game, read a configuration, process a log or produce a report, a program needs files. C handles files through streams: a stream is a source or destination of bytes that you read from or write to in order, and the standard library hides whether it's connected to a disk file, the terminal or a pipe.

In this lesson you'll learn how C represents an open file (FILE *), how to open files with the right mode, how to detect and report errors properly, why output is buffered and when to flush it, and how stdin, stdout and stderr fit in: they're streams too. The next lessons build on this with text files, binary files and error handling.

Note: Our editor runs each program in a fresh sandbox. Your program can create, read and delete files, but they exist only during that one run. The examples therefore write a file first and then read it back.

FILE pointers and streams

All file functions live in <stdio.h>. Opening a file gives you a pointer to a FILE object, an opaque structure the library uses to track the file: where you are in it, its buffer, whether an error or end-of-file has happened. You never look inside a FILE; you just pass the pointer to library functions.

The basic life cycle has three steps: open, use, close.

C Write a file, then read it back

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

  • fopen(path, mode) opens the file and returns a FILE *, or NULL if it can't.
  • fprintf(stream, format, ...) works exactly like printf (see Printing Output), but writes to the stream you pass.
  • fclose(stream) writes any buffered data, releases the file and frees the FILE. After fclose, the pointer is invalid: don't use it again.
  • fgets(buffer, size, stream) reads one line, at most size - 1 characters, and returns NULL at end of file. You know it from Reading Input; there it read from stdin.

The file name "greeting.txt" is a relative path, resolved against the program's current working directory. You can also use absolute paths like "/home/ana/notes.txt" or "C:\\data\\notes.txt" (in a C string, a Windows backslash must be written \\, and forward slashes also work on Windows).

File modes

The second argument to fopen says what you want to do with the file:

Mode Opens for If the file exists If it doesn't exist
"r" reading read from the start fails (NULL)
"w" writing erases it (truncates to length 0) creates it
"a" appending every write goes to the end creates it
"r+" reading and writing starts at the beginning, keeps contents fails
"w+" reading and writing erases it creates it
"a+" reading and appending reads anywhere, writes go to the end creates it

Two letters can be added:

  • b (as in "rb", "wb", "r+b") opens the file in binary mode. On Linux and macOS, binary and text mode behave the same. On Windows, text mode converts \n to \r\n when writing and back when reading, and treats byte 26 (Ctrl+Z) as end of file. Use b for any file that isn't plain text, as Binary Files explains.
  • x (C11), as in "wx" or "w+x", means exclusive creation: fopen fails if the file already exists, instead of erasing it. It's the safe way to create a new file without destroying someone's data.

Here are w, a and x in action:

C w truncates, a appends, x refuses

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

fgetc reads a single character and returns EOF at the end. It returns an int, not a char, so that EOF (a negative value) can be told apart from every valid byte; storing the result in a char is a classic bug. fputs(text, stream) writes a string without formatting and, unlike puts, adds no newline. The "wx" attempt on the existing log.txt fails with File exists; the message comes from strerror(errno), explained in the next section.

Warning: Mode "w" destroys the existing contents the moment fopen succeeds, before you write anything. Opening the wrong file with "w" is a quick way to lose data. Use "a" to add to a file, "r+" to modify it in place, or "wx" when you mean "create a new file".

Checking for errors

fopen can fail for many reasons: the file doesn't exist, you lack permission, the path is a directory, the disk is full, too many files are open. When it fails, it returns NULL and (on all common systems) sets errno to a code describing why. Using a NULL stream crashes the program, so check every fopen.

perror(prefix) prints your prefix, a colon and the system's description of the current errno to stderr. strerror(errno) from <string.h> gives the same text as a string, for building your own messages:

C Reporting why fopen failed

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

You'll see missing/settings.ini: No such file or directory and opening . for writing: Is a directory on stderr. The exact wording comes from the operating system, so it differs between Linux, macOS and Windows. Save errno in a variable right away if you need it later, because any library call, even printf, may change it.

A good error message names the file and the reason. "Error!" helps nobody; "config.ini: Permission denied" tells the user exactly what to fix. Error Handling goes deeper into errno, return codes and cleanup.

Errors while reading and writing

Opening isn't the only thing that can fail. Every stream keeps two flags you can test:

  • feof(stream) is true after a read tried to go past the end of the file.
  • ferror(stream) is true after a read or write error (a disk failure, a full disk, a removed USB stick).

The typical pattern reads until a function signals "nothing more", then checks why:

C
int ch;
while ((ch = fgetc(f)) != EOF) {
    /* use ch */
}
if (ferror(f)) {
    perror("read error");
} else {
    /* feof(f) is true: we simply reached the end */
}

Don't write while (!feof(f)) as the loop condition. feof only becomes true after a read has failed, so that loop processes one extra, invalid "character" or line at the end. Always test the return value of the read function itself.

Stream error state: ferror, feof and clearerr

Every FILE * carries two sticky flags: an end-of-file flag and an error flag. They are set by failed reads and writes, and they stay set until something clears them. This is the third function in the family:

Function Meaning
feof(f) Nonzero if a read has hit the end of the file.
ferror(f) Nonzero if a read or write has failed.
clearerr(f) Resets both flags to zero.

Reaching the end of a file is a normal event, while an error is not, and the two flags let you tell them apart after a loop ends. clearerr is for the cases where you want to try again.

Stale error flags. The flags are not cleared by later successful operations. A successful fseek clears the end-of-file flag and rewind clears both flags, but nothing else does, and on modern libraries a stream that has already reported end-of-file keeps returning EOF without even looking at the file again. If your program recovers from a problem (a full disk has been cleaned up, a network share is back, a user closed another program), you must call clearerr before retrying, or every call fails immediately.

The classic use is following a growing file, as tail -f does. One stream writes a log; another reads it and reaches the end. When more text arrives, the reader has to clear its end-of-file flag to see it:

C Following a file with clearerr

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The first pass reads started and stops with feof=1. The second pass reads nothing, even though working is now in the file, because the library remembers that the stream already hit the end. After clearerr, the line appears. (Some older C libraries would have re-checked the file on every call; the C standard does not require either behavior, so call clearerr and your program works everywhere.)

An error flag you can see

A write to a stream opened read-only fails, and that sets the error flag. This is a safe way to watch the flag change:

C ferror and clearerr on a read-only stream

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The sequence is ferror=0, the failing fputc, ferror=1, then ferror=0 after clearerr. The read works at the end because the stream itself was never damaged; only the flag was set. In a real program, do not blindly clear errors and carry on. First report the problem with perror, and clear the flag only when you have a reason to believe a retry can succeed.

Closing files and fclose errors

Every successful fopen must be matched by exactly one fclose. A program that forgets loses data that's still sitting in the buffer if it crashes, and it can run out of file handles: operating systems limit how many files a process may have open (often 1,024 on Linux).

fclose returns 0 on success and EOF on failure. Failure is rare, but for files you write it matters: buffered data is written during fclose, so a full disk may only be reported there. For important output, check it:

C
if (fclose(out) != 0) {
    perror("saving report.txt");    /* the file may be incomplete */
    return 1;
}

When main returns or exit is called, all open streams are flushed and closed automatically, but relying on that hides errors and keeps files open longer than needed. Close files as soon as you're done with them.

Buffering and fflush

Writing to a disk one character at a time would be slow, so streams are buffered: fprintf and friends collect data in memory and the library writes it out in large blocks. There are three buffering modes:

  • Fully buffered: data is written when the buffer fills (often 4 KB or more) or the stream is flushed or closed. Files use this mode.
  • Line buffered: data is written at each newline. stdout uses this mode when it's connected to a terminal.
  • Unbuffered: data is written immediately. stderr is always like this, so error messages appear right away.

fflush(stream) forces buffered output to be written now. Use it before something that might take a long time or crash, or when another program is reading the file at the same time. setvbuf changes the mode or buffer size, but you rarely need it.

C stdout is buffered, stderr is not

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Our editor collects the two streams separately and shows everything from stderr after all of stdout, so you can't see the timing here. The program's output goes to a pipe, not a terminal, so stdout is fully buffered and only written when it's flushed or the program ends. In a terminal, you'd see line 2 printed before line 1, since line 1 waits in stdout's buffer for a newline while stderr writes at once. This ordering surprise is why debugging output often goes to stderr, or why programs call fflush(stdout) before printing to stderr.

stdin, stdout and stderr are streams

Three streams are open when your program starts, already of type FILE *:

Stream Purpose Usually connected to
stdin standard input keyboard, or a file/pipe with <
stdout standard output the terminal, or a file/pipe with >
stderr error messages the terminal, even when stdout is redirected

printf(...) is just fprintf(stdout, ...), and getchar() is fgetc(stdin). Because they're ordinary streams, a function that takes a FILE * can write to the screen or to a file without changing a line:

C One function, any stream

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

write_report doesn't know or care where its output goes. This is a pattern worth copying: take a FILE * parameter instead of hard-coding printf, and your function works for the terminal, files and, in tests, temporary files. ftell tells you the current position in the stream; Binary Files covers it with fseek and rewind.

On the command line, users redirect these streams without any code changes: ./report > out.txt sends stdout to a file while stderr still shows errors on screen, and ./report < data.txt makes stdin read from a file.

Removing, renaming and temporary files

<stdio.h> also has a few functions for managing files as a whole:

  • remove(path) deletes a file. It returns 0 on success.
  • rename(old, new) renames or moves a file. Whether an existing new file is replaced depends on the system (POSIX replaces it; Windows fails).
  • tmpfile() creates a temporary file opened in "wb+" mode that's deleted automatically when it's closed or the program ends.
C rename, remove and tmpfile

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

A common safe-save technique combines these: write the new data to a temporary file in the same directory, fclose it and check for errors, then rename it over the old file. If anything fails midway, the original file is still intact.

C's standard library has no functions for directories (listing, creating or deleting them) or for file sizes and permissions. Those come from the operating system: POSIX functions like opendir, mkdir and stat on Linux and macOS, or the Windows API.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. data.txt contains 3 lines. What happens after FILE *f = fopen("data.txt", "w"); succeeds?

    Mode "w" truncates an existing file to length 0 as soon as it's opened. Use "a" to append or "wx" to refuse existing files.
  2. 2. What does fopen return when the file can't be opened?

    fopen returns NULL on failure, and on common systems sets errno, which perror and strerror turn into a readable message.
  3. 3. Why is while (!feof(f)) { fgets(line, sizeof line, f); ... } a bug?

    The end-of-file flag is set by a read that runs out of data. Test the read's return value (fgets != NULL) instead.
  4. 4. Why does fgetc return an int instead of a char?

    EOF is a negative int outside the range of unsigned char values. Storing the result in a char can make a real byte look like EOF, or EOF never match.
  5. 5. A program prints a progress message with printf("Working...") and then crashes. Why might the message never appear?

    stdout is buffered (line buffered in a terminal, fully buffered in pipes and files). Call fflush(stdout) or write to stderr when the message must appear immediately.

Summary

  • fopen(path, mode) returns a FILE * or NULL; always check it and report failures with perror or strerror(errno).
  • Modes: r read, w write (erases!), a append, + read and write, b binary, x (C11) exclusive creation.
  • fprintf, fputs and fgetc/fgets are the stream versions of printf, puts, getchar and line input; fgetc returns an int.
  • Loop on the read function's return value, then use ferror/feof to see why reading stopped.
  • fclose every file once; check its result for files you write.
  • Streams are buffered; fflush forces output out, and stderr is unbuffered.
  • stdin, stdout and stderr are FILE * streams, so functions that take a FILE * work with the screen and files alike.
  • remove, rename and tmpfile manage whole files; directories need operating-system APIs.

Next: Reading and Writing Text Files