C++ file-redirection

To use your code [1] you have to call your program like this:

App.exe < inputfile > outputfile

You can also use:

App.exe < inputfile >> outputfile

In this case the output wouldn't be rewritten with every run of the command, but output will be appended to already existing file.

More information about redirecting input and output in Windows you can find here.


Note that the <, > and >> symbols are to be entered verbatim — they are not just for presentation purposes in this explanation. So, for example:

App.exe < file1 >> file2

In addition to original redirection >/ >> and <

You can redirect std::cin and std::cout too.

Like following:

int main()
{
    // Save original std::cin, std::cout
    std::streambuf *coutbuf = std::cout.rdbuf();
    std::streambuf *cinbuf = std::cin.rdbuf(); 

    std::ofstream out("outfile.txt");
    std::ifstream in("infile.txt");

    //Read from infile.txt using std::cin
    std::cin.rdbuf(in.rdbuf());

    //Write to outfile.txt through std::cout 
    std::cout.rdbuf(out.rdbuf());   

    std::string test;
    std::cin >> test;           //from infile.txt
    std::cout << test << "  "; //to outfile.txt

    //Restore back.
    std::cin.rdbuf(cinbuf);   
    std::cout.rdbuf(coutbuf); 

}

Tags:

C++

File