What are C Standard Streams Explained- C Programming Tutorials For Beginners

🚀 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 8

C Standard Streams Explained

stdin, stdout and stderr: the three file pointers that exist before main() runs, and the map of C file I/O functions.

Before your main() function runs a single line, the C runtime has already opened three files for you. Understanding these standard streams in C explains why printf() works without an fopen(), why error messages can be separated from results, and how output reaches a UART on an embedded board. This lecture of our free C programming course introduces the streams, shows how buffering changes what you see, and ends with a map of the file I/O functions that the next lectures cover one by one.

The book presents this topic as a three-row table. We keep that table but add the missing pieces: descriptor numbers, buffering rules, shell redirection, and what happens when there is no screen at all, which is the normal situation in embedded C programming.

What You Will Learn

After this free C tutorial you can:

  • Name the three standard streams in C and the descriptors behind them.
  • Explain why stdout is buffered and stderr is not, and what that does to message order.
  • Redirect each stream independently from the shell.
  • Rewrite printf, scanf, getchar and putchar in terms of file functions.
  • Describe how standard output reaches a UART on bare-metal targets.
  • Recognise the five families of file I/O functions used in the rest of this chapter.

Prerequisites

You should have read the lectures on fclose() and on end of file. Familiarity with printf() and scanf() from the earlier input-output chapter is assumed.

The Three Standard Streams in C

Each stream is a pointer of type FILE *, declared in <stdio.h>. You use them exactly like a pointer returned by fopen(), but you never open or normally close them. The runtime does that around main().

StreamDescriptor (POSIX)Default deviceBufferingPurpose
stdin0KeyboardLine buffered on a terminal, otherwise fully bufferedInput to the program
stdout1ScreenLine buffered on a terminal, otherwise fully bufferedNormal results
stderr2ScreenUnbufferedErrors and diagnostics

Streams between your program and the outside world

Keyboard / file / pipe → stdin (fd 0) → Your program
 
Your program → stdout (fd 1) → Screen / file / UART
 
Your program → stderr (fd 2) → Screen / log / debug port

The word stream is the key. Your program does not care whether the other end is a keyboard, a disk file, a pipe from another program or a serial port. It reads and writes a sequence of bytes through a FILE *, and the system decides where those bytes really go. That is why a single source file can run unchanged on a desktop and on an embedded Linux board.

Seeing the Streams Work

The program below prints the descriptor behind each stream, then writes one message to stdout and one to stderr, and finally writes two characters to stdout with fputc() to show that the standard streams accept the same functions as any other file.

#include <stdio.h>

int main(void)
{
    printf("fileno(stdin)  = %d\n", fileno(stdin));
    printf("fileno(stdout) = %d\n", fileno(stdout));
    printf("fileno(stderr) = %d\n", fileno(stderr));

    fputs("normal message -> stdout\n", stdout);
    fputs("error message  -> stderr\n", stderr);

    fputc('O', stdout);
    fputc('K', stdout);
    fputc('\n', stdout);
    return 0;
}

Build it, then run it in three different ways to prove that stdout and stderr are separate:

gcc -Wall -Wextra -o ep_streams ep_streams.c
./ep_streams 2>/dev/null
./ep_streams >/dev/null
./ep_streams | cat

Output of ./ep_streams 2>/dev/null, which throws away stderr:

fileno(stdin)  = 0
fileno(stdout) = 1
fileno(stderr) = 2
normal message -> stdout
OK

Output of ./ep_streams >/dev/null, which throws away stdout:

error message  -> stderr

Output of ./ep_streams | cat, where stdout goes into a pipe:

error message  -> stderr
fileno(stdin)  = 0
fileno(stdout) = 1
fileno(stderr) = 2
normal message -> stdout
OK

Look at the last result. In the source file the stderr line comes after the three fileno lines, yet it is printed first. The reason is buffering. Because stdout is connected to a pipe rather than a terminal, the library holds its text in memory until the program ends. stderr is unbuffered and prints immediately. When you run the same program directly on a terminal, stdout is line buffered, so every line appears in program order.

Redirection: Choosing Where Each Stream Goes

The shell connects the streams before starting your program. Your code does not change at all.

Shell syntaxEffect
./prog > out.txtstdout goes to a file; stderr still shows on screen
./prog 2> err.txtstderr goes to a file; stdout still shows
./prog > all.txt 2>&1both streams go to the same file
./prog < in.txtstdin reads from a file instead of the keyboard
./prog1 | ./prog2stdout of the first becomes stdin of the second

This separation is the reason to print errors with fprintf(stderr, ...) or perror(). If a program writes its results to stdout and its complaints to stderr, a user can save the results in a file and still see the problems on the screen.

Standard Streams in C and Their Function Shortcuts

The functions you already know are shorthand for the file versions applied to the standard streams:

Short formEquivalent general formDifference
printf(...)fprintf(stdout, ...)None
scanf(...)fscanf(stdin, ...)None
putchar(c)putc(c, stdout)None
getchar()getc(stdin)None
puts(s)fputs(s, stdout)puts also adds a newline
perror(msg)fprintf(stderr, ...) plus the errno textAlways writes to stderr

Everything you learn about files in this chapter therefore applies to the keyboard and the screen too. A function that takes a FILE * works with a disk file, stdin and stdout alike, which makes your code easier to test.

Standard Streams in Embedded C Programming

On a desktop the operating system provides the terminal. On a bare-metal microcontroller there is none. The C library still defines stdout, and printf() still fills its buffer, but at the bottom of the chain it calls a low-level routine that you must supply. With newlib-style libraries that routine is commonly named _write, and its job is to send the bytes to something real.

Where printf() ends up on a bare-metal board

printf() → stdout buffer → _write() you provide
 
UART driver → TX pin → USB-serial adapter → Terminal on PC
  • UART retargeting: _write() loops over the bytes and writes each to the UART data register.
  • Semihosting: a debugger connection carries stdout to the host PC without a UART.
  • Embedded Linux: nothing special; stdout is the serial console or a log file.
  • Unbuffered debugging: stderr is handy for crash-time messages because it needs no flush.

Buffering and crashes

If a board resets while text is still inside the stdout buffer, that text is lost. When debugging a hang, end messages with a newline on a line-buffered stream, call fflush(stdout), or write them to stderr.

The Map of File I/O Functions

The remaining lectures in this chapter take the families one at a time. The book groups them as follows; the last column notes how portable each is.

FamilyFunctionsStandard C?Covered in
Character I/Ofgetc, fputc, getc, putcYesLectures 9 and 10
String I/Ofgets, fputsYesNext lectures
Integer I/Ogetw, putwNo (legacy)Lecture 11
Formatted I/Ofscanf, fprintfYesNext lectures
Record (block) I/Ofread, fwriteYesNext lectures

Common Mistakes and Troubleshooting

MistakeSymptomFix
Sending errors to stdoutError text lands in the results fileUse fprintf(stderr, ...)
Expecting program-order output when pipingstderr lines appear firstFlush stdout or use setvbuf()
Calling fclose(stdout)Later printf() calls print nothingDo not close it
Using gets()Buffer overflow, compiler errors on modern CUse fgets(buf, size, stdin)
No _write on bare metalprintf() compiles but prints nothingRetarget it to the UART

Best Practices for Standard Streams in C

  • Results to stdout, diagnostics to stderr, always.
  • Write helper functions that take a FILE * so the same code can print to the screen or to a log file.
  • End interactive prompts with a newline or call fflush(stdout) before reading from stdin.
  • On embedded targets, check how stdout is retargeted before relying on printf() for debugging.

Performance and security notes

Among the standard streams in C, a fully buffered stdout is faster because it makes fewer system calls, which is why piped programs run quicker than terminal ones. Unbuffered stderr costs one call per message, so do not print thousands of lines through it in a tight loop. Security-wise, never pass untrusted text as the format string, as in printf(user_text). Use printf("%s", user_text) or fputs(user_text, stdout).

Key Takeaways

Remember these points

  • The standard streams in C are stdin, stdout and stderr, opened before main().
  • On POSIX systems they use descriptors 0, 1 and 2.
  • stdout is buffered, stderr is not; this can reorder output when piping.
  • The shell can redirect each stream without changing your program.
  • printf, scanf, putchar and getchar are special cases of the file functions.
  • On bare-metal targets, you provide the low-level routine that connects stdout to hardware.

Conclusion

Once you see the standard streams in C as ordinary streams, file handling stops feeling like a separate topic. The same FILE * functions serve a disk file, a pipe, a serial console and the standard streams alike. The experiment with redirection and the piped run showed that stdout and stderr are independent, and the buffering difference explained the surprising order.

In the next lecture of this free embedded C course we start with the simplest file operation, writing a single character with fputc(), and use it to capture keyboard input into a file.

Frequently Asked Questions

What are the standard streams in C?

They are three FILE * objects, stdin, stdout and stderr, that the runtime opens for you before main() starts. They represent standard input, standard output and standard error.

What is the difference between stdout and stderr?

Both usually appear on the same screen, but they are separate channels. stdout carries normal results and is buffered; stderr carries diagnostics and is unbuffered. Because they are separate, a user can redirect one without the other.

What file descriptor numbers do the standard streams have?

On POSIX systems stdin is descriptor 0, stdout is 1 and stderr is 2. You can confirm this with fileno(), as the example program does.

Why does my stderr text appear before my stdout text when I pipe the output?

When stdout is not a terminal it is fully buffered, so its text waits in memory until the buffer fills or the program ends. stderr is unbuffered and appears at once. Call fflush(stdout) or use setvbuf() if the order matters.

Where does printf output go on a microcontroller?

Nowhere until you provide a low-level write routine. Bare-metal C libraries such as newlib expect you to supply one, typically named _write, that pushes bytes to a UART, a debug port or a semihosting channel.

Should I call fclose(stdout)?

Almost never. After it, any printf() loses its output. The runtime closes the standard streams at program exit; closing them yourself is only for special cases such as daemons.

Is gets() the same as fgets(stdin, …)?

No, and you should not use gets() at all. It cannot limit the input length and was removed from the C language in C11. Use fgets(buf, size, stdin).

Continue the Free Embedded C Course

Next: write characters into files with fputc, read them back with fgetc, then store integers with putw and getw.

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

2 Comments

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 →