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
As mentioned by our pal Wikipedia, we can use the
dup2 system call in C to manage a similar thing!
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.
foobar.txt, add th following:
As for the contents of
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:
readto read in a character and assign it to variable
fd2, we move one character further along in the text file.
fd1once and then we redirect
fd2one last time, but after redirection the value now reads "o".
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
Now if we run
gcc two.c && ./a.out, we get the following:
In this case, we do the following:
foobar.txtfile to file descriptor
scanfto assign the values to
c2have been assigned the words "foobar" and "test" respectively!
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.
Image credit: Michael Kubler