Skip to content
Tutorials Center
My learning

Topics

Lesson 71 of 135 ยท File Input and Output

Reading and Writing Text Files

Write text files with fprintf and fputs, read them line by line with fgets, parse fields with sscanf and strtok, and count lines, words and characters in C.

Most files a program touches are text files: configuration files, logs, CSV exports, source code, reports. In C they're just a stream of characters with a '\n' at the end of each line, and you work with them using the same family of functions you already know from the keyboard and screen: printf becomes fprintf, fgets reads from any FILE *, and sscanf parses what you read.

In File Handling Basics you learned to open and close files and to check that fopen worked. This lesson is about what happens in between: writing formatted text, reading it back line by line, and turning lines into data. You'll also build a small word counter and a CSV reader that survives bad input.

Every example creates its own file first, because files on our server only exist while one program runs.

Writing text: fprintf, fputs and fputc

There are three writing functions, from most to least powerful:

Function Writes Adds a newline?
fprintf(fp, format, ...) formatted text, exactly like printf only if your format has \n
fputs(str, fp) a string as is no (unlike puts)
fputc(ch, fp) one character no

printf(...) is literally fprintf(stdout, ...), so every format specifier from Printing Output with printf works with files too.

C Writing a report with fprintf

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 output is a neat table because %-8s left-aligns the name in 8 columns and %6.2f right-aligns the score in 6. Two details matter here:

  • ch is an int, not a char. fgetc returns every possible byte value (0 to 255) plus EOF (usually -1), and only an int can hold all 257 of them. Storing the result in a char is a classic bug: the loop either never ends or stops early at a byte that happens to look like -1.
  • The fclose result is checked. Output is buffered, so a full disk often only shows up when fclose flushes the last block.

Note: Text mode and binary mode are identical on Linux and macOS. On Windows, text mode translates "\n" to the two bytes \r\n when writing and back when reading. Writing "\n" in your code is always correct; the C library handles the platform's convention. The details are in Binary Files.

Reading line by line with fgets

fgets(buffer, size, fp) reads characters until it has stored a newline, reached the end of the file, or filled size - 1 characters, and then adds the terminating '\0'. It returns buffer on success and NULL at end of file (or on an error). That makes the standard loop very short:

C
char line[256];
while (fgets(line, sizeof line, fp) != NULL) {
    /* use line */
}

The newline is kept in the buffer, which is usually not what you want when you print or compare the line. strcspn(line, "\n") returns the index of the first newline (or the string length if there is none), so writing a '\0' there removes it safely in both cases.

C Numbering the lines of a file

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 output shows four lines, including the empty third line (0 chars) and the last line, which has no newline in the file but is still read correctly. After the loop, ferror tells apart "the file ended" from "reading failed"; fgets returns NULL in both cases.

Lines longer than the buffer

If a line has more than size - 1 characters, fgets stops early and the rest of the line arrives in the next call. You can detect that: a complete line ends with '\n', a cut-off line doesn't (unless it is the very last line of a file without a trailing newline). Programs that must accept any line length either use a big buffer and reject longer lines, or grow a buffer with realloc as described in Dynamic Memory. POSIX systems also offer getline, which allocates the buffer for you, but it isn't part of standard C.

C Detecting a line that did not fit

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 long name arrives in three pieces: "Maximilianu", "s-Bartholom" and finally "ew" with its newline. When a partial line is an error in your program, report it, then skip the rest of the line by reading with fgetc until you see '\n' or EOF.

Reading formatted data with fscanf

fscanf(fp, format, ...) is scanf for files. It returns the number of items it converted, or EOF if the input ended before the first conversion. That makes it handy for files you control that contain only whitespace-separated values:

C Summing numbers with fscanf

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.

It prints 5 values, sum 72.25, average 14.45. fscanf skips spaces and newlines between numbers, so line structure doesn't matter. Change one value in the file to abc and run it again: the loop stops at the bad token, because fscanf returns 0 and leaves abc unread.

That last point is why fscanf is fragile for real-world files. After a failed conversion, the file position is in the middle of a line, there's no easy way to say which line was wrong, and %s without a width can overflow a buffer just like scanf (see Reading Input with scanf and fgets). For anything a human might edit, use the safer pattern in the next section.

The robust pattern: fgets, then parse the line

Read a whole line with fgets, then pick it apart with sscanf, strtol/strtod (Converting Strings and Numbers) or strtok (String Functions). A bad line can't confuse the next one, and you always know the line number for your error message.

Here is a small CSV reader for name,quantity,price lines. It skips comments and blank lines and reports every malformed line instead of stopping:

C A forgiving CSV reader

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.

Three good rows are printed (pencil, notebook, ruler) with a stock value of 156.00, and two error messages go to stderr for lines 5 and 6. A few tricks in the format string are worth learning:

  • %49[^,] is a scanset: it reads up to 49 characters that are not commas. The width keeps name from overflowing.
  • The trailing %c tries to read one more non-space character. If it succeeds, n is 4, which means the line had junk after the price (like 1.20xyz), so it's rejected too.
  • strcspn(line, "\r\n") removes both \n and a \r left behind when a file written on Windows is read on Linux.

Warning: This simple reader doesn't handle real-world CSV features like quoted fields ("Smith, John") or commas inside values. For data you don't control, use a proper CSV library or write a small state machine that tracks whether you're inside quotes.

Splitting lines into words

strtok splits a string at any of the delimiter characters you give it. Combined with fgets, it gives you a word counter in a few lines. The program below counts lines, words and characters, like the Unix wc tool:

C Counting lines, words and characters

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.

It reports 4 lines, 20 words, 108 characters and the longest word, characters. The character count includes the newlines, just like wc -c. Notice the double space after newline;: strtok treats a run of delimiters as one separator, so it doesn't produce empty words. That's great for words but wrong for CSV, where a,,b has an empty middle field; that's one more reason the CSV reader above uses sscanf instead.

strtok changes the string it splits (it writes '\0' over the delimiters) and remembers its position in a hidden static variable, so you can't use it on two strings at once (for example, splitting lines into fields and fields into parts). For that, POSIX offers strtok_r, which keeps its position in a variable you pass in; standard C itself has no re-entrant version outside the optional Annex K. Within one loop like this, plain strtok is fine.

Appending and updating text files

Mode "a" opens a file for appending: every write goes to the end, even if you move the file position. It's the right mode for logs. Text files can't be edited in place easily, because changing "7" to "12" would need to shift every byte after it. The standard technique is to read the old file, write a new temporary file, then remove the old one and rename the new one into place:

C
FILE *in = fopen("todo.txt", "r");
FILE *out = fopen("todo.tmp", "w");
/* ... check both, copy lines from in to out, changing what you need ... */
fclose(in);
if (fclose(out) == 0) {
    remove("todo.txt");               /* rename over an existing file fails on Windows */
    rename("todo.tmp", "todo.txt");
}

If the program crashes halfway, the original file is still intact, which is exactly why editors and databases save this way.

C Appending to a log file

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.

Each call opens, appends and closes, so the log keeps all three lines. Reopening for every line is slow for a busy program; real loggers keep the file open and call fflush after important messages.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why should the result of fgetc be stored in an int rather than a char?

    EOF is a negative int that must be distinguishable from every valid byte. Squeezing the result into a char either merges EOF with a real byte or makes the loop never end.
  2. 2. A file contains abc (no newline). What does fgets(buf, 4, fp) store in buf?

    fgets reads at most size - 1 = 3 characters and always adds the terminator. A final line without a newline is still returned; the next call hits end of file and returns NULL.
  3. 3. Which value does sscanf("7,2.5", "%d,%lf %c", &a, &b, &c) return?

    The integer and the double are converted. Then %c finds no more characters and the end of the string stops it, so the result is 2 conversions, which is how the CSV reader knows there was no trailing junk.
  4. 4. Your fgets loop ended. How do you tell whether the file simply ended or a read error happened?

    fgets returns NULL in both cases. ferror (or feof) on the stream tells you which one happened.
  5. 5. What is the safest way to change one line in the middle of a text file?

    Overwriting in place only works when the new text has exactly the same length. Writing a new file and renaming it is reliable and keeps the original safe if something fails halfway.

Summary

  • fprintf, fputs and fputc write formatted text, strings and characters to any FILE *; check fclose when writing, because buffered data is written there.
  • fgetc returns an int so it can report EOF; never store it in a char.
  • while (fgets(line, sizeof line, fp) != NULL) is the standard line loop. Strip the newline with line[strcspn(line, "\n")] = '\0', and use ferror after the loop to detect read errors.
  • A line without '\n' at the end of the buffer didn't fit (or is the last line of the file).
  • fscanf is fine for simple whitespace-separated data you control; for human-edited files, read lines with fgets and parse them with sscanf (with widths and scansets like %49[^,]), strtol or strtok.
  • Mode "a" appends; to edit a text file, write a temporary copy and rename it over the original.

Next: Binary Files, where you'll store numbers and structs as raw bytes with fread, fwrite and fseek.