C's Standard Input and Output Redirection


Introduction

Standard input and output redirection in C allows you to change the source of input and the destination of output for your programs. This guide explores the concepts of input and output redirection and provides sample code to demonstrate how to use them.


Standard Input Redirection

Standard input (stdin) can be redirected to read from a file instead of the keyboard. This is helpful for processing data stored in files or for automated testing. You can use the `<` operator to specify the input file.


// Redirect input from a file
./myprogram < input.txt

Standard Output Redirection

Standard output (stdout) can be redirected to write to a file instead of the terminal. This is useful for saving program output to a file or generating logs. You can use the `>` operator to specify the output file.


// Redirect output to a file
./myprogram > output.txt

Sample Code

Let's create a simple C program that reads from standard input and writes to standard output. We will demonstrate how input and output redirection can be used to process data from files.


#include <stdio.h>
int main() {
int number;

// Read from standard input
while (scanf("%d", &number) != EOF) {
// Process the data
printf("Received: %d\n", number);
}
return 0;
}

Suppose we have an input file named "data.txt" containing numbers:


10
20
30

We can redirect the program's input and output as follows:


// Redirect input from "data.txt" and output to "result.txt"
./myprogram < data.txt > result.txt

After running this command, "result.txt" will contain the processed data:


Received: 10
Received: 20
Received: 30

Conclusion

Standard input and output redirection in C provides flexibility in reading and writing data from different sources and destinations. This guide introduced the concepts and provided sample code to demonstrate how redirection works. By using these techniques, you can make your programs more versatile and capable of handling various data sources and destinations.