简体   繁体   English

将stdout和stderr重定向到文件中

[英]redirect the stdout and stderr into a file

I want to redirect the output of a system call into a file .. I tried this.. 我想 系统调用的输出重定向文件中

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

But this is only working for system calls .. If i put some other thing in place of ls , the error output is not redirected into the file.. it is just printed on the console .. 但这仅适用于系统调用 ..如果我将其他东西代替ls ,则错误输出不会重定向到文件中。它只是打印在console ..

For example 例如

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

I want the error output redirected to the file.. how can i do this? 我想将错误输出重定向到文件。我该怎么办? thanks.. 谢谢..

it can be achieved by 它可以通过

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

This will direct both standard output and standard error to the file temp.txt.. 这会将标准输出和标准错误都定向到文件temp.txt。

while

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

This will only direct standard output to temp.txt.. 这只会将标准输出定向到temp.txt。

NOTE: 注意:

The greater-than sign should not be separated by spaces from the number of the file descriptor. 大于号不应与文件描述符的编号之间用空格分隔。 If it would be separated, we would be pointing the output to a file again. 如果要分开,我们将再次将输出指向文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM