1

我正在编写代码以将标准输出重定向到文件(例如将 ls 返回到文件的结果),并且 dup2() 函数不会重定向我的输出。这是我拥有的代码:

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;
}

这不起作用。我只是将 ls 的输出输出到我的终端窗口。我已采取措施检查 dup2() 确实返回 1,而不是 -1。

4

1 回答 1

3

您需要在分配周围加上一对括号,否则它是对布尔表达式的分配(如果文件确实可以打开,则返回 0):

if ((newfd = creat("fout.txt", O_TRUNC | O_WRONLY)) == -1)
于 2014-03-01T21:36:42.617 回答