我正在编写代码以将标准输出重定向到文件(例如将 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。