CSSE 132 Mini-reading · I/O Part 2

Linux I/O Part 2: Reading Lines with fgets

Trace characters, newlines, and string boundaries before processing a text file. Allow about 7–9 minutes.

Why This Matters

Part 1 follows byte counts and file positions. Worksheet 19 shifts to text: reading keyboard input, predicting what fits in an array, and finding a column within a line. These tasks depend on distinguishing a newline in the input from the null character that ends a C string.

Core Idea

fgets(buffer, size, stream) reads text into an existing character array. For the positive sizes used here (at least 2), it stores at most size − 1 input characters and appends '\0' on success. The size argument must fit within the actual array; fgets cannot discover the array's capacity for you.

A call stops when it has filled those size − 1 positions, read a newline, or reached end of file. If it reads '\n', that newline is stored too. The appended '\0' takes another slot but does not come from the input stream. A newline means “end of this line”; a null character means “end of this string.”

On success, fgets returns buffer's address. It returns NULL when no characters can be read at end of file, or when a read error occurs. Test the return value before printing or inspecting the buffer. A final line without a newline still produces a successful read if it contains characters.

Worked Examples

1. Trace capacity and unread input

Consider this short snippet, assuming the read succeeds:

char buffer[8];
fgets(buffer, 6, stdin); // at most five input characters
printf("%s", buffer);   // prints until '\0'

The array has eight slots, but this call uses a limit of six. Only five slots are available for input. Each row below is a separate run; \n represents one newline character, not two printed symbols.

Input typed, then EnterStored from index 0Still unreadOutput
ABA B \n \0Nothing from this lineAB followed by a newline
ABCDEA B C D E \0\nABCDE, without a newline
ABCDEFGA B C D E \0F G \nABCDE, without a newline

Other array positions are unchanged; fgets does not clear the whole array. In the second run, another successful fgets reads the leftover newline and stores \n \0. In the third, it reads F G \n \0. Input that did not fit is still in the stream. Even when a call returns successfully, you may have read only part of a line.

2. Repeat a line read from a file

This complete example counts the characters in each chunk. Use a text file whose lines contain at most 30 characters before the newline if you want each call to return a whole line.

Read, inspect, then repeat
C codeWhat this does
#include <stdio.h>

int main(int argc, char **argv) {

Include the stream declarations and begin a standard C program.

    if (argc != 2) return 1;
    FILE *input = fopen(argv[1], "r");
    if (input == NULL) {
        perror("fopen");
        return 1;
    }

Require a filename, open it for reading, and check the handle before using it.

    char buffer[32];
    while (fgets(buffer, sizeof buffer, input) != NULL) {

Reserve 32 bytes. Each successful call stores at most 31 input characters, then a null terminator. The return value is a pointer, not a byte count.

        int i = 0;
        while (buffer[i] != '\0') ++i;
        printf("%d characters: %s", i, buffer);
    }

Count characters until the null terminator and print the chunk. A retained newline counts as a character and moves the output to the next line.

    int failed = ferror(input);
    if (fclose(input) != 0) failed = 1;
    return failed ? 1 : 0;
}

Check for a read error and close the stream. NULL can mean end of file or a read error.

Run it as ./line-count notes.txt. For a file containing Sun\nMoon\n, the output is 4 characters: Sun and 5 characters: Moon, each followed by its retained newline. The null terminator is excluded from the count. Empty files produce no output. Longer lines appear as multiple chunks; this program does not join them together.

3. Change a string boundary

Worksheet 19 processes a table one row at a time. After a successful read, the buffer is a string you can inspect using an index. For example, suppose it contains Oak 42\n\0. Indices 0–2 hold Oak, index 3 holds a space, and index 4 starts the next field.

buffer[3] = '\0'; // replace the space, not the next field
printf("%s\n", buffer);

This prints Oak and a newline. The characters after index 3 remain in memory, but %s stops at the new terminator. Changing the array does not move the file position or put characters back into the stream.

To locate a boundary rather than assume its index, begin at index 0, inspect the current character, and advance while the string has not ended. Test for the separator before advancing again. Never continue past '\0'. Use that reasoning to complete the worksheet's loop yourself.

The worksheet calls its example a CSV file but explicitly assumes a single space between columns. Follow that assumption for the exercise; a comma is not its separator. Also assume each whole row fits in the worksheet's buffer. Repeated fgets calls alone do not guarantee one row per call when a row is too long.

Common Mistakes

Counting the terminator as input

A size of 6 permits five input characters plus a null. A retained newline uses one of those five input positions.

Expecting Enter to disappear

The newline is stored if it fits. Otherwise it stays unread. Adding another newline when printing a complete line can create blank lines.

Treating the return as a count

fread returns an item count; fgets returns a pointer or NULL. Inspect the string only after success.

Assuming the array was cleared

Only the characters read and the appended terminator are supplied on success. Unused slots are not automatically zeroed.

Quick Reference

QuestionReminder
How much fits?At most size − 1 input characters, then '\0'.
What ends a read?Capacity limit, a newline (retained), or EOF.
Keyboard versus file?Use stdin or an opened FILE * as the third argument.
How to repeat?while (fgets(buffer, sizeof buffer, input) != NULL) for a local array.
Where does %s stop?At the first '\0', not at a space or newline.

Check Yourself

  1. A successful fgets uses size 7 and input XY followed by Enter. Which characters are stored?
  2. With size 4 and input WXYZ followed by Enter, what does the first call store and leave unread?
  3. Why can printing a line with printf("%s\n", buffer) produce a blank line?
  4. A buffer contains "Elm 9\n". What changes after buffer[3] = '\0', and what remains?
  5. Why must you test fgets's result before processing the buffer?

Answers

Show the answers
  1. X, Y, '\n', '\0'. Remaining array positions are unchanged.
  2. W, X, Y, '\0'; Z and '\n' remain unread.
  3. The buffer may already contain a newline, so the format adds a second one.
  4. The space becomes a null, so %s prints Elm. The later characters remain in memory and the stream position is unchanged.
  5. NULL means no successful string is available from that call. Use ferror afterward to distinguish an error from normal end of file.

Next Step

Try Worksheet 19: Input/Output II. Label the array capacity, size argument, stored newline, null terminator, and unread input before filling in the code.