Undo redirect of stdout with dup2
<p>The following code is writing both "A" and "B" to the file "out.txt", with the first call to open returning 3 and second call returning 4.</p>

<p>What I expected is for "A" to be written to the file and "B" to be written to the screen. I also expected open to return 3 in each case.</p>

<p>What should I do to fix the code below:  </p>

<pre><code>int main(int argc, char** argv)
{
    int file = open("out.txt", O_APPEND | O_WRONLY);
    if(file != 3)    return 1;

    if(dup2(file,1) &lt; 0)    return 1;
    std::cout &lt;&lt; "A" &lt;&lt; std::endl;

    if(dup2(1,file) &lt; 0)    return 1;
    std::cout &lt;&lt; "B" &lt;&lt; std::endl;

    file = open("out.txt", O_APPEND | O_WRONLY);
    if(file != 3)    return 1;

    return 0;
}
</code></pre>
