Search code examples
c++linuxunixstdio

Redirecting input and output files on Unix and C++ using stdio


I need to do this:

$ ./compiledprog.x < inputValues > outputFile

so that I read from the file inputValues which for our case might just be \n separated int values or whatever. Then anything printf()'d goes into outputFile. But what's this called, technically speaking, and where can I find a demo of doing this.


Solution

  • As noted by others, it's input/output redirection.

    Here's an example program that would copy the standard input to the standard output, in your example copy the contents from inputValues to outputFile. Implement whatever logic you want in the program.

    #include <unistd.h>
    #include <iostream>
    using std::cin;
    using std::cout;
    using std::endl;
    using std::cerr;
    
    #include <string>
    using std::string;
    
    int main(int argc, char** argv) {
            string str;
    
            // If cin is a terminal, print program usage
            if (isatty(fileno(stdin))) {
                    cerr << "Usage: " << argv[0] << " < inputValues > outputFile" << endl;
                    return 1;
            }
    
            while( getline(cin, str) ) // As noted by Seth Carnegie, could also use cin >> str;
                    cout << str << endl;
    
            return 0;
    }
    

    Note: this is quick and dirty code, which expects a well behaved file as input. A more detailed error checking could be added.