How does fgets Reading Lines Safely- C Programming Course For Engineering Students

🚀 Learn BLE on Linux (BlueZ) – Programming Part 1

Hands-on Bluetooth Low Energy course. Special price: ₹399

Enroll Now on Udemy →
💬 Need help or career guidance? Ask us!Contact Us →

Free C Programming Course | Files | Lecture 15

fgets Reading Lines Safely

Master fgets in C: the bounded, newline-aware way to read text from files and the keyboard, with tested examples for embedded C programming.

In this part of our free C tutorial we study fgets in C, the function you should reach for whenever a program has to read a line of text. Configuration files, serial command lines, log parsers and menu inputs in embedded C programming all start with the same question: how do I read a line without overflowing my buffer? fgets answers it by taking the buffer size as an argument.

The behaviour has a few details that trip up beginners: the newline is kept, a short buffer splits one line into several reads, and a NULL return can mean two different things. We will test every one of them, so that by the end of this lecture of the free embedded C course you can write a line reader that never breaks.

What You Will Learn

  • The declaration of fgets and exactly how many characters it reads.
  • Why the newline stays in your buffer and how to remove it.
  • What happens when the line is longer than the buffer.
  • How to tell end of file from a read error.
  • How to build a small key=value configuration reader.
  • Why fgets replaces gets in all modern code.

Prerequisites

  • The previous lecture on fputs, because we reuse the notes.txt file created there.
  • Arrays of char, string terminators and the strlen function.
  • Using strcspn and strchr from string.h at a basic level.

How fgets in C Reads a Line

char *fgets(char *s, int n, FILE *stream);

fgets copies characters from the stream into s and stops as soon as one of three things happens: it has stored n-1 characters, it has just stored a newline, or the stream has no more data. Then it writes a ‘\0’ after the last character, so s is always a valid string. The extra byte reserved for the terminator is the reason the limit is n-1, not n.

The three stopping conditions of fgets

start → read next char → stop if n-1 stored → stop after \n stored → stop at end of file → append \0

Return value

fgets returns the pointer s when it stored something. It returns NULL when it hit end of file before reading any character, or when a read error occurred. Because both end of file and error give NULL, you separate them afterwards with feof(fp) and ferror(fp).

Reading a File Line by Line

This program prints every line of notes.txt with a line number. The call to strcspn finds the position of the first newline in the buffer and we overwrite it with ‘\0’. If the line has no newline, strcspn returns the string length and the assignment simply rewrites the existing terminator, so the trick is safe in both cases.

#include <stdio.h>
#include <string.h>

int main(void)
{
    char buf[80];
    int n = 0;
    FILE *fp = fopen("notes.txt", "r");

    if (fp == NULL) {
        perror("fopen");
        return 1;
    }

    while (fgets(buf, sizeof buf, fp) != NULL) {
        buf[strcspn(buf, "\n")] = '\0';
        printf("%d: %s\n", ++n, buf);
    }

    if (ferror(fp))
        perror("fgets");

    fclose(fp);
    return 0;
}
$ gcc -Wall -Wextra -o ep_fgets_read ep_fgets_read.c
$ ./ep_fgets_read
1: Yesterday is history
2: Tomorrow is mystery
3: Today is a gift

Why the newline matters: if you skip the strip and then compare a line with strcmp against the word “start”, the comparison fails because your buffer holds “start\n”. Many “my command is never recognised” bugs come from exactly this.

What If the Buffer Is Too Small?

fgets never overflows the buffer, so a long line is delivered in pieces. The next call continues where the previous one stopped. You can detect an unfinished line by checking whether the last stored character is a newline. Our second program uses a deliberately tiny buffer of 8 bytes, so each call can hold 7 characters.

#include <stdio.h>
#include <string.h>

int main(void)
{
    char buf[8];
    int chunk = 0;
    FILE *fp = fopen("notes.txt", "r");

    if (fp == NULL) {
        perror("fopen");
        return 1;
    }

    while (fgets(buf, sizeof buf, fp) != NULL) {
        size_t len = strlen(buf);
        int complete = (len > 0 && buf[len - 1] == '\n');
        buf[strcspn(buf, "\n")] = '\0';
        printf("chunk %d [%s] %s\n", ++chunk, buf,
               complete ? "end of line" : "line continues");
    }

    fclose(fp);
    return 0;
}
$ ./ep_fgets_small
chunk 1 [Yesterd] line continues
chunk 2 [ay is h] line continues
chunk 3 [istory] end of line
chunk 4 [Tomorro] line continues
chunk 5 [w is my] line continues
chunk 6 [stery] end of line
chunk 7 [Today i] line continues
chunk 8 [s a gif] line continues
chunk 9 [t] end of line

One 20-character line read through a 7-character window

line → Yesterday is history\n
calls → call 1: no newlinecall 2: no newlinecall 3: newline found

Count the first chunk: “Yesterd” is 7 characters, which is n-1 for n = 8. The line “Yesterday is history” has 20 characters plus a newline, so it needs three calls. A real program keeps appending chunks until it sees the newline, or it makes the buffer large enough for the longest line the protocol allows and rejects anything longer.

Build a Key=Value Configuration Reader

Here is a practical example you can reuse in embedded Linux projects: reading a small settings file. Lines starting with ‘#’ are comments, blank lines are skipped, and each remaining line must contain an equals sign.

#include <stdio.h>
#include <string.h>

int main(void)
{
    char line[64];
    FILE *fp = fopen("device.cfg", "r");

    if (fp == NULL) {
        perror("fopen");
        return 1;
    }

    while (fgets(line, sizeof line, fp) != NULL) {
        line[strcspn(line, "\r\n")] = '\0';

        if (line[0] == '#' || line[0] == '\0')
            continue;

        char *eq = strchr(line, '=');
        if (eq == NULL) {
            printf("skipped bad line: %s\n", line);
            continue;
        }

        *eq = '\0';
        printf("key=<%s> value=<%s>\n", line, eq + 1);
    }

    fclose(fp);
    return 0;
}

Create the settings file first, then run the program:

$ printf '# device settings\nbaud=115200\n\nmode=fast\nbroken line\nname=node-7\n' > device.cfg
$ gcc -Wall -Wextra -o ep_cfg_reader ep_cfg_reader.c
$ ./ep_cfg_reader
key=<baud> value=<115200>
key=<mode> value=<fast>
skipped bad line: broken line
key=<name> value=<node-7>

We strip both \r and \n so the program also accepts files edited on Windows. This detail alone saves hours when a configuration file travels between machines.

fgets vs gets vs scanf

FunctionSize limitKeeps newlineReads spacesStatus
fgetsYes (n-1)YesYesRecommended
getsNoNoYesRemoved in C11
scanf(“%s”)Only with a widthLeaves it in inputNo, stops at spaceUse with care

fgets reads from any stream. To read from the keyboard, pass stdin: fgets(buf, sizeof buf, stdin). Printing a line that still has its newline? Use fputs(buf, stdout). If you use puts instead, you get an extra blank line, because puts adds a newline of its own.

fgets in Embedded and Real-World Code

  • Parsing configuration and calibration text files on embedded Linux boards.
  • Reading replies from a modem or GPS receiver that arrive as text lines.
  • Building simple command shells over a serial console, where each typed command is a line.
  • Reading /proc and /sys files such as /proc/cpuinfo line by line during diagnostics.

On microcontrollers without a standard filesystem, FatFs provides f_gets with a similar contract, so everything you learn here transfers.

Common Mistakes and Troubleshooting

MistakeResultFix
Using sizeof on a pointer parameterReads only 8 (or 4) bytesPass the real buffer length as a separate argument
Forgetting to strip the newlinestrcmp and atoi surprisesbuf[strcspn(buf, “\n”)] = ‘\0’;
Assuming one call equals one lineSplit or merged recordsCheck for the newline in the buffer
Treating NULL as “end of file” onlySilent read errorsTest ferror(fp) after the loop
Last line without newlineWrongly flagged as incompleteAccept it when feof is set
Passing n = 1Nothing is ever readUse a sensible buffer, 64 or more for text lines

Best Practices, Performance and Security

  • Always call fgets with sizeof on a real array, never with a guessed number that can drift from the declaration.
  • Treat input as untrusted. After reading a line, validate length and content before converting numbers with strtol.
  • Reject over-long lines instead of silently truncating them when the data is a command or a path.
  • fgets uses the stdio buffer, so reading line by line from a file is efficient even for large logs.
  • For embedded devices with limited RAM, pick the smallest buffer that fits your protocol and document the maximum line length.

Key Takeaways and Conclusion

Summary

  • fgets reads at most n-1 characters and always adds a null terminator.
  • The newline is kept when it fits; strip it with strcspn.
  • A too-small buffer splits a line into pieces, never a buffer overflow.
  • NULL means end of file or error, so check feof and ferror.
  • fgets replaces gets everywhere in modern code.

Reading lines safely is the foundation of every text parser you will write. With fputs from the last lecture and fgets from this one you can already save and reload text records. Next, we handle numbers and mixed data with fprintf, which writes formatted output straight into a file. Keep following this free C programming course for more hands-on, tested lessons.

Frequently Asked Questions

Why does fgets read only n-1 characters?

One byte is reserved for the null terminator. With a buffer of 8 bytes, fgets stores at most 7 characters, which our test confirmed with the chunk “Yesterd”.

Does fgets remove the newline character?

No. The newline is stored in the buffer if the line fits. Remove it with buf[strcspn(buf, “\n”)] = ‘\0’.

What does fgets return at the end of the file?

It returns NULL. A NULL can also mean a read error, so call feof or ferror to see which one happened.

How do I read a line that is longer than my buffer?

Call fgets again. Each call continues from where the previous stopped. Keep going until the buffer ends with a newline or the file ends.

Why is fgets safer than gets?

fgets takes the buffer size, so it cannot write past the end of the array. gets has no such limit and was removed from the C standard in C11.

Can fgets read from the keyboard?

Yes. Pass stdin as the stream: fgets(buf, sizeof buf, stdin).

Next: Formatted File Output

Write numbers, strings and structure fields into files with fprintf in the next lecture of this free embedded C course.

💬 Need help or career guidance? Ask us!Contact Us →

1 Comment

Leave a Reply

Your email address will not be published. Required fields are marked *

×

🚀 BLE on Linux (BlueZ)

Hands-on course. Only ₹399

Enroll Now →