Course contentsShow
← C
Lesson 676 of 1,21910. Input and OutputFree lesson

The concept of a stream in C

The concept of a stream in C

What you'll learn: How C uses the concept of a "stream" to handle data flow between your program and the outside world.

The Data Pipeline

In C, you don't usually talk directly to your keyboard or your screen. Instead, C uses an abstraction called a stream.

Think of a stream like a physical water pipe connecting two points. On one end, you have a source (like a keyboard), and on the other, a destination (like your program). Data flows through this pipe one byte at a time, in a specific order. Your program doesn't need to know if the pipe is connected to a mechanical keyboard, a touchscreen, or even a file on a disk; it just knows that if it opens the pipe, data will flow through.

The Three Standard Streams

When your C program starts, the operating system automatically opens three "pipes" for you. You don't have to set them up; they are just there, ready to use:

  1. stdin (Standard Input): The data flowing into your program. Usually, this is what you type on your keyboard.
  2. stdout (Standard Output): The data flowing out of your program. Usually, this is the text you see on your terminal screen.
  3. stderr (Standard Error): A dedicated pipe for error messages. Even if you redirect your normal output to a file, error messages usually still show up on the screen so you can see them immediately.

Streams in Action

Functions like printf and scanf are actually just wrappers that talk to these streams. When you use printf, you are pouring characters into the stdout stream.

#include <stdio.h>

int main() {
    // printf sends data to the 'stdout' stream
    printf("Hello, Stream!\n");

    // Under the hood, stdout is like a file that is always open
    fprintf(stdout, "This is the same as printf.\n");

    return 0;
}

Why use Streams?

The beauty of the stream concept is uniformity. Because C treats almost everything as a stream, the way you read a character from a keyboard is nearly identical to the way you read a character from a text file. The stream acts as a universal translator, so your program can focus on the data rather than the hardware details.

Key takeaway

A stream is a logical path for data to flow sequentially into or out of your program, acting as a bridge between your code and external devices.