Question

I am writing code to redirect stdout to a file(such as the result of an ls being returned to a file) and the dup2() function does not redirect my output. Here is the code that I have:

void testDup()
{
    int newft;
    if(newfd = creat("fout.txt", O_TRUNC|O_WRONLY) == -1)
    {
        cout << "Open failed"<< endl;
        exit(1);
    }
    dup2(newfd, 1);
    cout << "this should be in the new file" < endl;
}

And this does not work. I just get the output of ls to my terminal window. I have taken steps to check that dup2() did indeed return 1, and not -1.

Was it helpful?

Solution

You need a pair of parenthesis around the assignment, otherwise it's an assignment to a boolean expression (which returns 0 if the file could indeed be opened):

if ((newfd = creat("fout.txt", O_TRUNC | O_WRONLY)) == -1)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top