对于任何一个C程序,都对应有stdin, stdout, stderr这三种由C语言标准库定义的三个标准流。默认情况下,这三个流都指向终端,重定向(redirection)就是将这三种流重新指向其他位置。
第一种情况的写法为:
对stdin,stdout,stderr这三种流进行重定向的形式共有五种:
- 将stdout重定向于stderr
- 将stderr重定向于stdout
- 将stdout重定向于文件
- 将stderr重定向于文件
- 将stdout和stderr重定向于同一个文件
下面是一个简单的程序
#include<stdio.h>
int main(int argc,char *argv[])
{
fprintf(stdout,"This is an useless info sent to stdout.\n");
fflush(stdout);
fprintf(stderr,"This is an useless info sent to stderr.\n");
return 0;
}
第一种情况的写法为:
./main 1>&2
输出结果为:
bash-4.2@redirection$ ./main 1>&2
This is an useless info sent to stdout.
This is an useless info sent to stderr.
第二种情况的写法为:
./main 2>&1
输出结果为:
This is an useless info sent to stdout.
This is an useless info sent to stderr.
第三种情况的写法为:
./main 1>outfile
输出结果为:
bash-4.2@redirection$ ./main 1 > outfile
This is an useless info sent to stderr.
bash-4.2@redirection$ cat outfile
This is an useless info sent to stdout.
bash-4.2@redirection$
第四中情况的写法为:
./main 2>errfile
输出结果为:
bash-4.2@redirection$ ./main 2>errfile
This is an useless info sent to stdout.
bash-4.2@redirection$ cat errfile
This is an useless info sent to stderr.
bash-4.2@redirection$
第五种情况的写法为:
./main 2>errfile 1>&2
或者是:
./main 1>outfile 2>&1
输出结果为:
bash-4.2@redirection$ ./main 1>outfile 2>&1
bash-4.2@redirection$ ./main 2>errfile 1>&2
bash-4.2@redirection$ cat errfile
This is an useless info sent to stdout.
This is an useless info sent to stderr.
bash-4.2@redirection$ cat outfile
This is an useless info sent to stdout.
This is an useless info sent to stderr.
本文详细介绍了C语言标准库中的stdin、stdout、stderr三种流,并解释了如何通过重定向实现不同输出目的。
863

被折叠的 条评论
为什么被折叠?



