Course contentsShow
← C
Lesson 1095 of 1,21915. Systems ProgrammingFree lesson

Redirecting output with dup2()

Redirecting output with dup2()

What you'll learn: How to use the dup2() system call to point a standard file descriptor toward a file, effectively "silencing" the terminal and sending data elsewhere.

The "Plumbing" of I/O

Think of your program’s file descriptors as a row of wall sockets. By default, socket 1 (STDOUT) is plugged into your terminal screen. When you call printf, the program sends data through that socket, and it appears on your monitor.

dup2() is like a professional plumber’s tool. It allows you to unplug a socket and wire it to something else entirely—like a text file—without the rest of your program ever realizing the change happened.

Using dup2()

The function signature is int dup2(int oldfd, int newfd);. In plain English, this says: "Make newfd a copy of oldfd." If newfd was already open, the system closes it first to make room for the new connection.

If we want to redirect output to a file, we first open that file to get its descriptor, then use dup2 to copy that descriptor onto slot 1.

#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>

int main() {
    // 1. Open a file for writing
    int file_desc = open("output.txt", O_WRONLY | O_CREAT | O_TRUNC, 0644);

    // 2. Redirect STDOUT (1) to our file descriptor
    // This makes '1' point to the same place as 'file_desc'
    dup2(file_desc, STDOUT_FILENO);

    // 3. Close the original file descriptor (we don't need two copies)
    close(file_desc);

    // 4. This will NOT print to the screen; it goes into output.txt!
    printf("Hello, world! I am hidden in a file.\n");

    return 0;
}

Why this matters

The magic of dup2() is that it happens at the system level. The printf function doesn't know it's writing to a file; it just keeps sending data to descriptor 1 as it always has.

This is exactly how the shell handles the > operator. When you run ./myprog > log.txt, the shell forks a process, uses dup2() to swap the child's STDOUT with the file, and then executes your code. It’s a powerful way to reroute data streams without changing a single line of your core logic.

Key takeaway

dup2(file_fd, 1) replaces the terminal output with a file, rerouting all future printf calls to that file automatically.