Heading image

This short post is a recount of an exploration into redirection in the C language.

As always, let’s go to our friend Wikipedia to set the definition for us:

In computing, redirection is a form of interprocess communication, and is a function common to most command-line interpreters, including the various Unix shells that can redirect standard streams to user-specified locations.

In Unix-like operating systems, programs do redirection with the dup2(2) system call, or its less-flexible but higher-level stdio analogues, freopen(3) and popen(3).

Basic redirection can use < to redirect input and > to redirect output.

For example, we can use the redirect output operator to redirect the output from echo "Hello!" into a file example.txt.

As mentioned by our pal Wikipedia, we can use the dup2 system call in C to manage a similar thing!

A simple example

In our first example, we are going to write a simple example of two variables that open a foobar.txt that iterates character by character.

Inside of foobar.txt, add th following:

As for the contents of one.c:

The comments in the code explain what is happening in order, but we’re just going to print out the result by running gcc one.c && ./a.out. The output binary a.out is the name given since we do not provide output to GCC.

To explain further what is going on:

  1. We assign fd1 and fd2 to open foobar.txt.

A more readable example

The above can seem hard to comprehend — it is better playing around with this stuff in C. This example, I decided to use scanf to read in from stdin in the second example because I feel like the example was a little clearer for me.

Note: Given I knew the length of the words in the file, I just set a max STR_LEN of 6 as opposed to some dynamic calculation.

Create a file two.c.

Now if we run gcc two.c && ./a.out, we get the following:

In this case, we do the following:

  1. Allocate memory for c1 and c2.

Hooray! Redirection to stdin is a success (and no segmentation faults).

I will likely redo this exercise in Rust and Golang this week to show the how-to.


  1. Computer Systems A Programmer’s Perspective — Page 944

Image credit: Michael Kubler

Originally posted on my blog.

Senior Engineer @ Culture Amp. Tinkerer and professional self-isolator in 2020.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store