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

Standard stream redirection in shells

Standard stream redirection in shells

What you'll learn: How to use shell operators to divert your C program's standard input and output to files without changing your code.

The plumbing of a program

Imagine your C program as a water filtration box. It has an intake pipe (stdin) and two output pipes: one for clean water (stdout) and one for waste or alerts (stderr). By default, the intake is connected to your keyboard, and both output pipes pour directly into your terminal window.

Redirection is the act of unscrewing these pipes and attaching them to tanks (files) instead. The magic is that the program inside the box has no idea the pipes have been moved; it just keeps pumping data as usual.

Using the shell operators

In most terminal shells (like Bash or Zsh), you use special symbols to reroute these streams when you run your compiled program.

  1. Output Redirection (>): This takes everything printf would normally show and writes it to a file.
  2. Input Redirection (<): This feeds a file into scanf or fgets as if you were typing it manually.
#include <stdio.h>

int main() {
    char name[50];
    // This reads from stdin (keyboard OR redirected file)
    if (scanf("%49s", name) == 1) {
        // This writes to stdout (screen OR redirected file)
        printf("Hello, %s!\n", name);
    }
    return 0;
}

If you compile this as hello, you can run it normally: ./hello. But you can also "replumb" it:

  • To a file: ./hello > output.txt (The screen stays blank; the greeting goes into the file).
  • From a file: ./hello < name.txt (The program reads the name from the file instead of waiting for you to type).
  • Both: ./hello < name.txt > output.txt (A completely automated process).

Why this matters

Redirection is a pillar of the Unix philosophy. It allows you to write simple C programs that focus on logic, while the user decides where the data comes from and where it goes. It’s how developers process massive log files or chain multiple programs together—by treating files as virtual keyboards and screens.

Key takeaway

Use < to feed a file into your program's input and > to capture your program's output into a file.