🚀 Learn BLE on Linux (BlueZ) – Programming Part 1
Hands-on Bluetooth Low Energy course. Special price: ₹399
Enroll Now on Udemy →fputc in C: Write Characters
Write one character at a time into a file, check for errors, and learn when putc is not the same as fputc.
The simplest thing a program can do with a file is put one character into it. fputc in C does exactly that, and because everything else in file output is built on the same idea, understanding it well makes the rest of the chapter easy. In this lecture of our free C programming course you will write characters to a file, copy keyboard input into it, see why the return value matters and learn how fputc(), putc() and putchar() relate to each other.
The source book gives one short program that copies typed text to a file and mentions that Ctrl+Z ends the input on DOS and Ctrl+D on Unix. We keep the idea but rewrite the example, test it with a pipe so the result is repeatable, and look inside the resulting file byte by byte.
What You Will Learn
In this free C tutorial you will:
- Write the signature of fputc in C and explain each part.
- Interpret its return value and handle write errors.
- Copy standard input into a file with
getchar()andfputc(). - Verify file contents with command-line tools.
- Choose between
fputc,putc,putcharandfputs. - Avoid the common mistakes with stream modes and side effects.
Prerequisites
You should know how to open and close files (fopen(), fclose()), understand that stdin and stdout are streams, and recognise EOF. If any of those feel new, read the previous three lectures of this free embedded C course first.
fputc in C: Syntax and Return Value
int fputc(int c, FILE *stream);
The first argument is the character to write. It is declared int, but the function converts it to unsigned char, so only the low eight bits matter: asking it to write the value 0x141 stores the byte 0x41, which is the letter A. The second argument is the stream, normally a pointer returned by fopen() in a writing mode, or stdout.
| Outcome | Return value | Side effect |
|---|---|---|
| Success | The character written, as an int in the range 0 to 255 | File position moves forward by one |
| Failure | EOF | Error indicator set; errno describes the cause |
The book says the character is written “at the current file position” and the position then increases. That is correct for modes w and r+. In append mode (a) every write goes to the end of the file regardless of the position.
Path of one character through fputc
Capturing Keyboard Input With fputc
Here is a small tool, ep_capture. It first writes a fixed banner line using fputc() in a loop, then copies everything arriving on standard input until end of input, and finally reports how many characters it copied. It uses putc() for the copy to show that the two functions behave alike.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* ep_capture: copy standard input into a file, one character at a time. */
int main(int argc, char *argv[])
{
if (argc != 2) {
fprintf(stderr, "usage: %s <outfile>\n", argv[0]);
return EXIT_FAILURE;
}
FILE *out = fopen(argv[1], "w");
if (out == NULL) {
perror(argv[1]);
return EXIT_FAILURE;
}
/* part 1: a fixed banner written with fputc */
const char *banner = "# capture\n";
for (size_t i = 0; i < strlen(banner); i++) {
if (fputc(banner[i], out) == EOF) {
perror("fputc");
fclose(out);
return EXIT_FAILURE;
}
}
/* part 2: copy stdin until end of input (Ctrl+D on a terminal) */
long copied = 0;
int c;
while ((c = getchar()) != EOF) {
if (putc(c, out) == EOF) {
perror("putc");
break;
}
copied++;
}
fclose(out);
printf("copied %ld characters into %s\n", copied, argv[1]);
return EXIT_SUCCESS;
}
Build it and feed it two lines through a pipe, so the test is repeatable:
gcc -Wall -Wextra -o ep_capture ep_capture.c
printf 'hello\nworld\n' | ./ep_capture cap.txt
cat cap.txt
copied 12 characters into cap.txt
# capture
hello
world
To type the input yourself, run ./ep_capture cap.txt, type some lines, then press Ctrl+D on an empty line. Now look at the exact bytes in the file with od -c:
od -c cap.txt
0000000 # c a p t u r e \n h e l l o \n
0000020 w o r l d \n
0000026
The final number, octal 26, is 22 in decimal: ten banner characters plus twelve copied ones. There is no extra byte for Ctrl+D. This is the correction to the old book, which shows a ^Z stored in its output file; on Linux the end-of-input key is consumed by the terminal and never becomes data.
Reading the program line by line
fopen(argv[1], "w")creates the file or empties an existing one. TheNULLcheck withperror()reports the real reason if it fails.- The banner loop calls
fputc()once per character and stops at the firstEOFresult. int cis anintbecausegetchar()can returnEOF.fclose(out)flushes the buffer. Without it the last characters might never reach the file after a crash.
When fputc in C Fails
The second program tries something that cannot work: writing to a stream that was opened only for reading. It demonstrates how to detect and report the failure.
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
/* fputc on a stream opened read-only must fail. */
int main(void)
{
FILE *fp = fopen("cap.txt", "r");
if (fp == NULL) {
perror("cap.txt");
return EXIT_FAILURE;
}
if (fputc('X', fp) == EOF)
printf("fputc failed: %s\n", strerror(errno));
else
puts("fputc worked");
printf("ferror(fp) = %s\n", ferror(fp) ? "set" : "clear");
fclose(fp);
return 0;
}
gcc -Wall -Wextra -o ep_modefail ep_modefail.c
./ep_modefail
fputc failed: Bad file descriptor
ferror(fp) = set
Two pieces of evidence are available: the return value EOF and the stream’s error indicator, which ferror() reads. The text comes from strerror(errno). Other typical causes in real products are a full file system, a write-protected card, or a device that was unplugged.
Buffered failures arrive late
Because of buffering, a disk-full error may not show up on the call that caused it. It can appear many calls later, or only when fclose() flushes. In critical code, check both.
fputc, putc, putchar and fputs Compared
| Function | Writes | To which stream | Notes |
|---|---|---|---|
fputc(c, fp) | One character | Any | Always a real function |
putc(c, fp) | One character | Any | May be a macro; keep the stream argument free of side effects |
putchar(c) | One character | stdout | Same as putc(c, stdout) |
fputs(s, fp) | A whole string, without the terminating zero | Any | No newline added |
fwrite(p, n, k, fp) | A block of bytes | Any | Best for binary data and bulk output |
The book explains the difference between putc() and fputc() as “macro versus function”. Modern libraries blur that line, but the rule that follows from it still holds: never write putc(c, files[i++]), because the macro might evaluate i++ twice.
Real-World Uses of fputc in Embedded C Programming
- Custom log formatters: a logger writes a timestamp, a level and a message one character at a time into a ring of output files.
- Protocol dumps: a diagnostic tool writes each received frame as hexadecimal text, using
fputc()for separators. - Stream filters: a command-line tool reads from stdin, transforms each character (for example removing carriage returns from a serial capture) and writes to stdout.
- Retargeted output: on a bare-metal board, a
FILEobject backed by a UART lets existingfputc(c, uart)calls send bytes to hardware.
Common Mistakes and Troubleshooting
| Mistake | Symptom | Fix |
|---|---|---|
Opening with "r" and then writing | fputc returns EOF, “Bad file descriptor” | Open with "w", "a" or "r+" |
Opening with "w" when you meant to add | Old content disappears | Use "a" to append |
| Not checking the return value | Silent data loss on a full disk | Compare the result with EOF |
Using char c for the input loop | Loop ends early on byte 0xFF, or never ends | Declare int c |
Forgetting fclose() | Missing tail of the file after a crash | Close or flush at safe points |
Side effects inside putc() arguments | Skipped or doubled stream elements | Compute the stream first, or use fputc() |
Best Practices for fputc in C
- Write short helper functions such as
write_line(FILE *fp, const char *s)instead of repeating loops. - Check the return value at least once per block of output, and always check
fclose(). - Use
fputs()for strings andfwrite()for blocks; keepfputc()for genuinely per-character work. - Open files in text mode for text and in binary mode (
"wb") for data, even if your platform treats them the same today.
Performance considerations
Per-character calls to fputc in C involve a function call and a buffer check each time. That is fine for log lines but wasteful for megabytes of data. If you profile an output loop and find it slow, replace it with fwrite() or increase the buffer with setvbuf(). On flash-based storage, also avoid calling fflush() after every character, as each flush can cause a real write.
Security considerations
Never build an output file name from untrusted input without checking it, and be careful when writing data that came from the network: remember that a user-supplied string may contain newline characters that forge extra log lines. Filter or encode control characters before writing them.
Key Takeaways
Remember these points
- fputc in C writes one character and returns it, or
EOFon error. - The character is converted to
unsigned char; only eight bits are stored. - The stream must be open for writing, otherwise the call fails.
- Ctrl+D ends input on Linux and is never stored in the file.
putc()may be a macro; avoid side effects in its arguments.- Errors can surface late because of buffering, so check
fclose()too.
Conclusion
Writing a single character with fputc in C is easy, but doing it correctly means thinking about modes, return values and buffering. You built a capture tool, inspected its output byte by byte, and provoked an error on purpose to see how it is reported. You also corrected a belief from older books about end-of-input keys being stored in files.
In the next lecture of this free C programming course we do the reverse and read characters back with fgetc(), where the difference between char and int becomes a very practical issue on ARM targets.
Frequently Asked Questions
What does fputc do in C?
It writes one character, given as an int, to the output stream you name and advances the file position. The call is int fputc(int c, FILE *stream);.
What does fputc return?
On success it returns the character it wrote, converted to an unsigned char and then to int. On failure it returns EOF and sets the stream’s error indicator.
What is the difference between fputc and putc?
They do the same job. putc() is allowed to be implemented as a macro that evaluates its stream argument more than once, so you must not pass an expression with side effects such as files[i++]. fputc() is always a real function.
Why does fputc take an int instead of a char?
For symmetry with fgetc(), which must return an int so it can also return EOF. Inside fputc() the value is converted to unsigned char, so only its low eight bits are written.
Is Ctrl+D written into the file when I type it?
No. On Linux the terminal driver treats Ctrl+D as end of input and makes getchar() return EOF. The key itself never reaches your program as a character. Older DOS books show a visible ^Z in the file because of how that platform worked.
Can fputc write binary data?
Yes, as long as the file is opened in binary mode where the platform distinguishes it ("wb"). On Windows a text-mode stream would turn each newline byte into two bytes.
Is writing character by character slow?
Each call has some overhead, but the stdio buffer means the disk is not touched for every character. For large blocks, fwrite() is faster and clearer.
Keep Learning Embedded C for Free
Next: read characters with fgetc, find out why one wrong variable type breaks the loop on ARM, and save integers with putw and getw.

2 Comments