将stdout和stderr重定向到文件中

时间:2013-04-30 07:36:11

标签: c linux gcc io-redirection

我想系统调用的输出重定向文件 ..我试过了..

#include <stdio.h>
int main()
{
        system("ls >> temp.txt");
        return 0;
}

但这仅适用于系统调用 ..如果我在ls处放置其他东西,则错误输出不会重定向到文件中..它只是打印在console ..

例如

#include <stdio.h>
int main()
{
system("hello >> temp.txt");
return 0;
}

我想将错误输出重定向到文件..我该怎么做?感谢..

1 个答案:

答案 0 :(得分:3)

可以通过

来实现
system("hello > temp.txt 2>&1");

这会将标准输出和标准错误都指向文件temp.txt ..

,而

system("hello 2>&1 > temp.txt");

这只会将标准输出定向到temp.txt ..

注意:

大于号不应该用文件描述符号的空格分隔。如果将它分开,我们将再次将输出指向文件。