Shell之重定向

本文详细介绍了C语言标准库中的stdin、stdout、stderr三种流,并解释了如何通过重定向实现不同输出目的。
        对于任何一个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.

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值