John Oldman
John Oldman

Reputation: 99

How to redirect cout and cin?

I'm executing my program with the following command: ./myProgram -i test.in -o test.out

Both files are legal and exist.

// run all over the arguments and set the cin and cout if needed
for (int i = 1; i < argc; i= i+2)
{
    int j = i+1;

    // loop over each pairs of arguments
    do
    {
        // set cin
        if(argv[i] == "-i")
        {
            static std :: ifstream s_inF(argv[j]);
            std :: cin.rdbuf(s_inF.rdbuf());
            break;
        }

        //set cout
        if(argv[i] == "-o")
        {
            std::ofstream out(argv[j]);
            std::cout.rdbuf(out.rdbuf());
            break;
        }

        // in order to search for the other case
        // (example:X.out -i)
        int temp = i;
        i = j;
        j = temp;
    }while(i>j);
}

I wrote this block in main in order to redirect cin and cout according to char **argv. cin works just fine but cout does not. When I take it like that it works:

// run all over the arguments and set the cin and cout if needed
for (int i = 1; i < argc; i= i+2)
{
    int j = i+1;

    // loop over each pairs of arguments
    do
    {
        // set cin
        if(argv[i] == "-i")
        {
            static std :: ifstream s_inF(argv[j]);
          std :: cin.rdbuf(s_inF.rdbuf());
          break;
        }

        //set cout
        if(argv[i] == "-o")
            break;

        // in order to search for the other case
        // (example:X.out -i)
        int temp = i;
        i = j;
        j = temp;
    }while(i>j);
}

std::ofstream out(argv[4]);
std::cout.rdbuf(out.rdbuf());

What is causing the problem?

Upvotes: 1

Views: 1676

Answers (2)

Dietmar K&#252;hl
Dietmar K&#252;hl

Reputation: 153840

The stream whose stream buffer you installed to std::cout gets destructed right after installing the stream buffer:

std::ofstream out(argv[j]);
std::cout.rdbuf(out.rdbuf());

The first line needs to read

static std::ofstream out(argv[j]);

There may be other errors but this is the one I spotted.

Upvotes: 3

Ivaylo Strandjev
Ivaylo Strandjev

Reputation: 70929

It does not work because you need j to be i+1 for the redirecting of the output to work. Give it a try - what happens if you first pass the -o and then the -i in the first sample?

Change this:

        int temp = i;
        i = j;
        j = temp;

To this:

        int temp = i;
        i = j;
        j = temp + 1;

You will also have to work on the while condition.

By the way why do you need j at all? You can do it only with i and than use i+1 for the redirection. I believe this will also make the code easier to understand.

Upvotes: 0

Related Questions