🚀 Learn BLE on Linux (BlueZ) – Programming Part 1
Hands-on Bluetooth Low Energy course. Special price: ₹399
Enroll Now on Udemy →Reading Strings with fgets
Chapter 9, Lecture 8 of the free C programming course: safe string input for embedded C programming
Reading strings in C looks easy until the first user types a space. Then the program silently drops half the input, or worse, overruns a buffer and corrupts memory. This lecture of our free C programming course shows the safe, modern way to take text input: fgets(), with scanf() kept for simple single words and puts() for output. It is written for embedded C programming, where every input byte lands in a fixed-size buffer that you own.
Everything here targets the current C standard (C17/C23 behaviour) and is compiled with gcc -std=c17 -Wall -Wextra. If you are following this free C tutorial to prepare for firmware work, the habits you build now are exactly the ones used when reading a command line from a UART.
What You Will Learn
- Why
scanf("%s")stops at the first whitespace and what stays behind in the input buffer - Why
gets()was removed from the C language and what replaced it - How
fgets()works: size rule, newline handling, terminator guarantee, return value - How to strip the trailing newline with one line of standard C
- The difference between
puts(),fputs()andprintf()for strings - How the same idea maps to reading a line from a UART in C programming for embedded systems
Prerequisites
You should be comfortable with character arrays, the null terminator '\0' and the %s conversion from the earlier lectures of this chapter. If those feel shaky, revisit the string basics lectures first; this free embedded C course builds on them directly.
Why Reading Strings in C Is Tricky
A C string is just a run of char values ending in '\0'. The language has no string type, so the library function you pick decides where reading stops. scanf("%s") stops at any whitespace: space, tab or newline. That is perfect for reading one word such as a file name, and wrong for a sentence such as sensor board v2.
The diagram below shows what the keyboard buffer looks like when the user types that text and the program calls scanf("%31s", word). Blue cells are consumed by the call; grey cells stay behind for the next read.
Two consequences follow. First, the extra words are not lost; they remain in the stream and the next input call reads them immediately, which causes the classic bug where a program seems to skip a prompt. Second, you must put a width in the format (%31s for a 32-byte array) because plain %s has no idea how big your array is.
Width is size minus one
For char word[32] the format is %31s. The 32nd byte is reserved for the terminator that scanf appends itself.
gets() Is Gone: Use fgets() Instead
Older C books, including the reference this lecture series started from, teach gets() to read a line with spaces. That function has no size argument, so it cannot protect your buffer. It was deprecated in C99 and removed in C11. Modern compilers either refuse it or print a loud linker warning. Do not use it, even in toy programs.
| Function | Stops at | Size-safe? | Keeps newline? | Status |
|---|---|---|---|---|
gets(buf) | newline | No, unbounded | No | Removed in C11 |
scanf("%31s", buf) | whitespace | Yes, with width | No (left in stream) | Fine for one word |
fgets(buf, n, stdin) | newline or n-1 chars | Yes | Yes, if it fits | Recommended |
How fgets() Works for Reading Strings in C
The prototype is char *fgets(char *buf, int n, FILE *stream);. The rules are short enough to memorise:
- It reads at most
n - 1characters, so there is always room for the terminator. - It stops early after it stores a newline. The newline is kept in your buffer.
- It always writes
'\0'after the last stored character. - It returns
bufon success andNULLat end-of-file or on a read error.
Suppose the buffer holds 8 bytes and the user types ten letters followed by Enter. The call takes the first seven letters, terminates the string, and leaves the rest waiting. Nothing overflows.
Removing the trailing newline
When the whole line fits, the buffer ends with '\n' before the terminator. Printing it with puts() then gives a blank line, and comparing it with strcmp() against a plain word fails. The tidy one-liner is:
name[strcspn(name, "\n")] = '\0';
strcspn() returns the index of the first newline, or the string length if there is none, so the assignment is safe in both cases. This is better than the common name[strlen(name) - 1] = '\0', which damages an empty string and chops a real character when the input was too long to include a newline.
Example 1: Reading Strings in C with fgets()
Save this as ex8_fgets.c. It reads a full line, removes the newline, reports the length and prints the text with puts().
#include <stdio.h>
#include <string.h>
#define NAME_MAX_LEN 32
int main(void)
{
char name[NAME_MAX_LEN];
printf("Enter device name: ");
if (fgets(name, sizeof name, stdin) == NULL) {
puts("input error");
return 1;
}
/* fgets keeps the newline; replace it with '\0' */
name[strcspn(name, "\n")] = '\0';
printf("Stored : [%s]\n", name);
printf("Length : %zu\n", strlen(name));
puts("Printed with puts():");
puts(name);
return 0;
}
Build and run it:
$ gcc -std=c17 -Wall -Wextra -o ex8_fgets ex8_fgets.c
$ ./ex8_fgets
Expected output (the text after the first prompt is what you type):
Enter device name: Temp Sensor 01
Stored : [Temp Sensor 01]
Length : 14
Printed with puts():
Temp Sensor 01
The square brackets in the second line prove that no newline is left inside the string. The length is 14 because the space characters count, and the terminator does not.
puts(), fputs() and printf() compared
| Call | Adds newline? | Format parsing? | Typical use |
|---|---|---|---|
puts(s) | Yes, always | No | Print one line of text quickly |
fputs(s, stdout) | No | No | Print exactly the characters in s |
printf("%s", s) | Only if you add \n | Yes | Mix text with numbers |
printf(s) | Only if s contains it | Yes, dangerous | Never with user input |
Never pass user text as the format
printf(name) treats the user’s text as a format string. Input such as %x%x%x then reads garbage from the stack. Always write printf("%s", name) or puts(name).Example 2: scanf() Versus fgets() on the Same Input
The second program feeds the same sentence to both functions so you can see the difference. After the scanf call it drains the rest of the line with a small getchar() loop, otherwise the leftover text would be consumed by the fgets call that follows.
#include <stdio.h>
int main(void)
{
char word[32];
char line[32];
printf("scanf test, type: sensor board v2\n> ");
scanf("%31s", word);
printf("scanf got: [%s]\n", word);
int c;
while ((c = getchar()) != '\n' && c != EOF)
; /* discard rest of the line */
printf("fgets test, type: sensor board v2\n> ");
fgets(line, sizeof line, stdin);
printf("fgets got: [%s]", line);
return 0;
}
$ gcc -std=c17 -Wall -Wextra -o ex8_scanf_vs_fgets ex8_scanf_vs_fgets.c
$ ./ex8_scanf_vs_fgets
scanf test, type: sensor board v2
> sensor board v2
scanf got: [sensor]
fgets test, type: sensor board v2
> sensor board v2
fgets got: [sensor board v2
]
Notice the closing bracket on its own line in the last result. That is the kept newline, shown exactly because we printed with "[%s]" and no extra \n. This tiny experiment explains most beginner input bugs: scanf leaves characters behind, fgets takes the whole line.
Reading Strings in C on Real Embedded Hardware
A microcontroller has no stdin and no keyboard. Input arrives byte by byte from a UART interrupt or a DMA buffer. Firmware therefore writes its own small uart_read_line(char *buf, size_t n) that follows the same contract as fgets(): store at most n - 1 bytes, stop at newline, always terminate, report failure with a clear return value. If you learn that contract properly here, porting it to bare metal is a ten-minute job. The lab at the end of this chapter does exactly that with a command parser.
- Command consoles: a debug shell over serial where you type
led on. - AT-command modems: the modem answers with lines such as
OKor+CSQ: 21,0that you must read as strings. - Configuration over USB-CDC: a host tool sends
set rate 115200and the device parses it.
Common Mistakes When Reading Strings in C
| Mistake | What goes wrong | Fix |
|---|---|---|
Using gets() | No bound, buffer overflow, not even available in C11 | Use fgets(buf, sizeof buf, stdin) |
scanf("%s") without width | Overflow on long input | Add a width: %31s |
| Forgetting the newline in the buffer | strcmp(buf, "yes") never matches | Strip it with strcspn |
Mixing scanf then fgets | fgets returns the leftover newline immediately | Drain the line with a getchar loop |
sizeof on a pointer parameter | Gives 4 or 8, not the array size | Pass the size as a separate argument |
| Ignoring the return value | On EOF the buffer holds old data | Check for NULL |
Best Practices, Performance and Security
- When reading strings in C, always pass
sizeof buf(for a real array in scope) rather than a repeated magic number. - Check
fgets()forNULLbefore touching the buffer. - Detect an over-long line by checking whether the stored text ends with a newline; if not, drain the remainder so it is not parsed as the next command.
- Treat all input as untrusted. Reading strings in C with a fixed buffer plus a bounded read removes the oldest and most exploited class of C vulnerability, the stack buffer overflow.
- Performance:
fgets()reads in blocks through the stdio buffer and is faster than agetchar()loop on a hosted system. On a microcontroller, prefer reading from an interrupt-filled ring buffer so the main loop never blocks on the UART.
Key takeaways
- scanf
%sreads one whitespace-free word; always give it a width. gets()is removed from C11;fgets()is the replacement.- fgets keeps the newline, writes the terminator, and returns NULL on EOF.
buf[strcspn(buf, "\n")] = '\0';is the clean way to remove the newline.puts()adds a newline,fputs()does not.
Conclusion
You now know how to take text input without trusting the user: bound the read, keep room for the terminator, deal with the newline, and check the return value. These four habits cover most of what safe reading strings in C requires. The next lecture looks at what you can do once the string is in memory, starting with measuring it using strlen().
Frequently Asked Questions
Is gets() really removed from C?
Yes. It was deprecated in C99 and removed from the standard in C11. Some old libraries still ship it for compatibility, but compilers warn, and you should never use it.
Why does fgets keep the newline?
It stores every character it reads up to and including the newline, so you can tell a complete line from a truncated one. Remove it yourself when you do not want it.
What happens if the line is longer than my buffer?
fgets stores n-1 characters and terminates. The rest stays in the stream and will be returned by the next call, so you must drain or process it.
Can I use scanf for strings with spaces?
Only with a scan set such as %31[^\n], which reads until a newline. For most programs fgets is simpler and clearer.
Does fgets work on bare-metal microcontrollers?
Only if your C library provides stdin and a retargeted read function. Most firmware instead writes a small line reader that follows the same rules.
Why use strcspn instead of strlen to remove the newline?
strcspn is safe when the line is empty or has no newline. A strlen-minus-one approach can write outside the string in those cases.
Topics Covered
Continue the Free C Programming Course
Next up: measuring a string with strlen() and building your own version. Keep going with this free embedded C course, one lecture at a time.

2 Comments