🚀 Learn BLE on Linux (BlueZ) – Programming Part 1
Hands-on Bluetooth Low Energy course. Special price: ₹399
Enroll Now on Udemy →fputs String Writing in C
Understand how fputs in C writes text to a file, why it never adds a newline, and how to replace the unsafe gets-based pattern found in old textbooks.
This lecture of our free C tutorial is about fputs in C, the standard way to write a plain string into a file or any other stream. If you are building logs, configuration files or diagnostic dumps for embedded C programming on Linux, fputs is one of the most frequently used calls. It is short, fast and has two behaviours that surprise beginners: it does not append a newline, and it does not write the terminating null byte.
We will prove both facts by inspecting the bytes on disk, and we will correct an old habit. Many older books combine gets with fputs to copy typed text into a file. gets was removed from the C language in C11 because it cannot be used safely, so this free embedded C course teaches the modern pair, fgets and fputs, instead.
What You Will Learn
- The declaration of fputs and what its return value means.
- Why fputs never writes the null terminator and never adds a newline.
- The exact difference between puts, fputs and fprintf.
- How to copy keyboard input into a file safely using fgets and fputs.
- How to use fputs for logging to stdout and stderr.
- Mistakes that corrupt log files and how to avoid them.
Prerequisites
- fopen, fclose and the text modes “w”, “a” and “r”.
- Strings as null-terminated char arrays.
- Basic knowledge of stdin, stdout and stderr, covered earlier in this chapter.
How fputs in C Works
int fputs(const char *s, FILE *stream);
fputs walks along the string s, sends every character before the terminating ‘\0’ to the stream, and stops. The null byte is a marker for the end of the string in memory, not part of the text, so it is left out of the file. Nothing else is added.
What fputs copies from memory to the file
Return value
On success fputs returns a non-negative number. On failure it returns EOF. Some older books claim it returns the last character written, but the standard only promises “non-negative”, so write your checks as if (fputs(s, fp) == EOF) and do not depend on the exact number.
Your First fputs Program
The next program writes the same three boot messages twice. In the first file we include the newline inside each string. In the second file we forget it.
#include <stdio.h>
int main(void)
{
FILE *good = fopen("boot.log", "w");
FILE *glued = fopen("glued.txt", "w");
if (good == NULL || glued == NULL) {
perror("fopen");
return 1;
}
fputs("clock ready\n", good);
fputs("uart ready\n", good);
fputs("sensor ready\n", good);
fputs("clock ready", glued);
fputs("uart ready", glued);
fputs("sensor ready", glued);
fclose(good);
fclose(glued);
return 0;
}
Build, run and inspect
$ gcc -Wall -Wextra -o ep_fputs_basic ep_fputs_basic.c
$ ./ep_fputs_basic
$ wc -c boot.log glued.txt
36 boot.log
33 glued.txt
69 total
$ cat boot.log
clock ready
uart ready
sensor ready
$ cat glued.txt
clock readyuart readysensor ready
$ od -c boot.log
0000000 c l o c k r e a d y \n u a r t
0000020 r e a d y \n s e n s o r r e
0000040 a d y \n
Do the arithmetic once and you will never forget it. “clock ready” is 11 characters plus a newline, 12. “uart ready” is 10 plus one, 11. “sensor ready” is 12 plus one, 13. Total 36 bytes, so no null byte was stored. The glued file has exactly the same text minus three newlines, 33 bytes.
Rule of thumb: if you want one record per line, the newline must be part of the string you pass to fputs. The function will never supply it for you.
puts vs fputs vs fprintf
Three functions look similar, but each has a different contract. Choosing the right one avoids both bugs and wasted CPU cycles.
| Function | Destination | Adds newline | Interprets format codes |
|---|---|---|---|
| puts(s) | stdout only | Yes | No |
| fputs(s, fp) | Any stream | No | No |
| fprintf(fp, fmt, …) | Any stream | Only if fmt has \n | Yes |
| fwrite(p, size, n, fp) | Any stream | No | No (raw bytes) |
So fputs("hello\n", stdout) and puts("hello") produce the same output, while fputs("hello", stdout) leaves the cursor on the same line. When your text is a plain string with no variables inside, fputs is the cleanest tool because it does not parse a format string.
Copying Typed Text Into a File the Safe Way
Old programs read a line from the keyboard with gets, which strips the newline, and then write it with fputs, which does not add one. The result is a file where all lines run together. It also hides a more serious problem: gets has no way to know the size of your buffer, so a long input overwrites memory. That is why it disappeared from the language.
The modern pattern uses fgets, which takes the buffer size and keeps the newline. Because fgets keeps the newline, fputs reproduces the lines perfectly.
#include <stdio.h>
int main(void)
{
char line[80];
FILE *fp = fopen("notes.txt", "w");
if (fp == NULL) {
perror("fopen");
return 1;
}
printf("Type lines, finish with Ctrl+D\n");
while (fgets(line, sizeof line, stdin) != NULL) {
if (fputs(line, fp) == EOF) {
perror("fputs");
break;
}
}
fclose(fp);
return 0;
}
$ gcc -Wall -Wextra -o ep_line_copy ep_line_copy.c
$ ./ep_line_copy
Type lines, finish with Ctrl+D
Yesterday is history
Tomorrow is mystery
Today is a gift
(press Ctrl+D)
$ cat notes.txt
Yesterday is history
Tomorrow is mystery
Today is a gift
$ wc -c notes.txt
57 notes.txt
Data flow of the safe line-copy program
The loop ends when fgets returns NULL, which happens when you press Ctrl+D on Linux (Ctrl+Z then Enter on Windows). We will study fgets in detail in the next lecture. The file notes.txt is reused there.
fputs for Logging in Embedded C Programming
Because the destination is a parameter, one function serves many targets. Writing fputs("boot ok\n", stdout) prints to the console, fputs("fault\n", stderr) goes to the error stream, and a FILE pointer opened with “a” appends to a persistent log. On an embedded Linux board that logging file might live on flash storage, on a microcontroller project the same call is often redirected to a UART by retargeting the low-level write function of the C library. Libraries such as FatFs offer a similar f_puts function, so the habit you build here carries over.
Appending instead of overwriting
Mode “w” empties the file every time the program starts. For a log that must grow across runs, open it with “a”. Each fputs then lands at the end of the existing content.
Common Mistakes and Troubleshooting
| Mistake | What you see | Fix |
|---|---|---|
| Missing \n in the string | All records on one line | Add \n to each string, or use fprintf with a format that ends in \n |
| Expecting a trailing null in the file | Wrong size calculations | Remember only the characters are written |
| String array without a terminator | Extra garbage characters in the file | Make sure the array ends with ‘\0’ before calling fputs |
| Binary data containing zero bytes | File cut short | Use fwrite, fputs stops at the first \0 |
| Not checking fopen | Crash on NULL stream | Test the pointer before the first fputs |
| Log lost after a crash | Buffered text never reached disk | Call fflush(fp) after important lines |
Best Practices, Performance and Security
- Never pass user-supplied text as the format of fprintf. Writing
fprintf(fp, user_text)allows % codes inside the text to be interpreted.fputs(user_text, fp)treats it as plain data and is safe. - fputs skips format parsing, so it uses less CPU than fprintf for constant strings. On small targets that matters.
- Buffering means many small fputs calls do not cause many disk writes. The data goes out when the buffer fills, on fflush, or on fclose.
- Check the return value in code where a failed write matters, for example a full flash partition.
- Use fgets, never gets. If an exercise or book shows gets, replace it with fgets(buf, sizeof buf, stdin).
Key Takeaways and Conclusion
Summary
- fputs writes the characters of a string to any stream, excluding the null terminator.
- It never appends a newline; puts does, but only for stdout.
- The return value is non-negative on success and EOF on failure.
- Use fgets together with fputs for line copying; gets is gone from modern C.
- Prefer fputs over fprintf for plain text, both for speed and for safety.
fputs in C is one of those small tools that you will use for the rest of your career, from a first Hello World log to production diagnostics on an embedded Linux gateway. Practise by changing the demo so that it opens the log in append mode and adds a timestamp string before every line. In the next lecture of this free C programming course we read those lines back with fgets and learn how its size argument really works.
Frequently Asked Questions
Does fputs add a newline at the end of the string?
No. Only the characters before the null terminator are written. Include \n in your string when you want a line break. puts is the function that adds one.
Is the null character written to the file by fputs?
No. In our test, three strings of 11, 10 and 12 characters plus three newlines gave a 36-byte file, which proves the terminators were not stored.
What is the difference between puts and fputs?
puts writes to stdout and adds a newline. fputs writes to any FILE stream and adds nothing. Calling fputs with stdout and a string ending in \n behaves like puts.
Why should I avoid gets when copying text into a file?
gets cannot limit how many characters it stores, so long input overflows the buffer. It was removed in the C11 standard. Use fgets with sizeof on the buffer.
How do I append to an existing log with fputs?
Open the file with fopen(name, “a”). Every fputs call then adds text at the end without erasing earlier content.
Can fputs write binary data?
Not reliably. It stops at the first zero byte. Use fwrite for binary buffers.
Continue the Free Embedded C Course
Next lecture: reading lines back with fgets, including what happens when your buffer is smaller than the line.

2 Comments