gpt4 book ai didi

c++ - dup 不重定向

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:54:39 26 4
gpt4 key购买 nike

我正在编写代码以将 stdout 重定向到一个文件(例如 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。

最佳答案

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

if ((newfd = creat("fout.txt", O_TRUNC | O_WRONLY)) == -1)

关于c++ - dup 不重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22120661/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com