04-4输入流输出流及错误流和管道

标准输入输出流和错误流

创建.c文件

$ vi cio.c

cio.c的内容如下,其中scanf为输入流,printf为输出流,&为取地址符

#include <stdio.h>

int main()
{
        printf("hello world!\n");
        int a;
        scanf("%d",&a);
        printf("input value is : %d\n",a);
        return 0;
}

进行编译

$ gcc cio.c

$ ls
a.out  cio.c

$ ./a.out
hello world!
3
input value is : 3

实际上是包含stdin stdout stderr这三个文件的,以printf为例,它是已经封装好的。实际是用fprintf表示,首字母的f表示文件的意思

printf("please input the value a :\n");
fprintf(stdout,"please input the value a :\n");

同理,对于输入流

int a;
scanf("%d",&a);
fscanf(stdin,"%d",&a);

对于错误流

if(a<0){
    printf(stderr,"the value must > 0");
    return 1;
}

故总程序为

#include <stdio.h>
/*
 stdin
 stdout
 stderr
 */
int main()
{
        //printf("please input the value a :\n");
        fprintf(stdout,"please input the value a :\n");
        int a;
        //scanf("%d",&a);
        fscanf(stdin,"%d",&a);
        if(a<0){
                fprintf(stderr,"the value must > 0\n");
                return 1;
        }
        return 0;
}

验证

$ gcc cio.c
$ ls
a.out  cio.c

$ ./a.out
please input the value a :
2

$ ./a.out
please input the value a :
-3
the value must > 0

重定向机制

先编写一部分代码,实现i+j功能

#include <stdio.h>

int main()
{
        printf("input the int value i:\n");
        int i,j;
        scanf("%d",&i);
        printf("input the int value j:\n");
        scanf("%d",&j);
        printf("i+j=%d\n",i+j);
        return 0;
}

编译运行,得到i+j的值

$ gcc main.c
$ ls
a.out  main.c

$ ./a.out
input the int value i:
3
input the int value j:
5
i+j=8

接下来我们查看到当前目录只有a.out和main.c文件,开始重定向>>,让我们的值不是默认输出到终端,而是输出到新的txt文件中

$ls 
a.out main.c

$ ./a.out 1>> a.txt
3
5
//输入3,5之后没有数据显示
$ ls
a.out  a.txt  main.c

查看

$ cat a.txt
input the int value i:
input the int value j:
i+j=8

重定向也可以不用输入1,为双箭头,且每次的结果都保存在a.txt里面

./a.out 1>> a.txt
3
5
$ cat a.txt
input the int value i:
input the int value j:
i+j=8

$ ./a.out >> a.txt
3
4
$ cat a.txt
input the int value i:
input the int value j:
i+j=8
input the int value i:
input the int value j:
i+j=7

$ ./a.out >> a.txt
5 7
$ cat a.txt
input the int value i:
input the int value j:
i+j=8
input the int value i:
input the int value j:
i+j=7
input the int value i:
input the int value j:
i+j=12

同样也可以重定向etc

$ ls /etc
acpi                    initramfs-tools      presage.xml
adduser.conf            inputrc              product-info
adjtime                 insserv              profile
alsa                    insserv.conf         profile.d
alternatives            insserv.conf.d       protocols
apache2                 iproute2             proxychains4.conf
apm                     ipsec.conf           pulse
apparmor.d              ipsec.d              python
appstore.json           ipsec.secrets        python2.7
apt                     issue                python3
bash.bashrc             issue.net            python3.7
bash_completion         kernel               rarfiles.lst
bash_completion.d       kernel-img.conf      rc0.d
bindresvport.blacklist  laptop-mode          rc1.d
binfmt.d                ldap                 rc2.d
bluetooth               ld.so.cache          rc3.d
ca-certificates         ld.so.conf           rc4.d
ca-certificates.conf    ld.so.conf.d         rc5.d
calendar                libaudit.conf        rc6.d
chatscripts             libblockdev          rcS.d
cron.d                  libibverbs.d         rearj.cfg
cron.daily              libnl-3              resolv.conf
cron.hourly             libpaper.d           rmt
cron.monthly            libreoffice          rpc
crontab                 lightdm              rsyslog.conf
cron.weekly             lighttpd             rsyslog.d
cryptsetup-initramfs    live                 samba
crypttab                locale.alias         sane.d
cups                    locale.gen           securetty
dbus-1                  localtime            security
dde-dock                logcheck             selinux
debconf.conf            login.defs           sensors3.conf
debian_version          logrotate.conf       sensors.d
deepin                  logrotate.d          services
deepin-authenticate     lsb-release          shadow
deepin-installer.conf   lscolor-256color     shadow-
deepin-version          lvm                  shells
default                 machine-id           skel
deluser.conf            magic                smartd.conf
dhcp                    magic.mime           smartmontools
dictionaries-common     mailcap              smi.conf
dkms                    mailcap.order        snmp
dpkg                    manpath.config       ssh
emacs                   mdadm                ssl
environment             mime.types           staff-group-for-usr-local
environment.d           mke2fs.conf          strongswan.conf
firefox-esr             modprobe.d           strongswan.d
fonts                   modules              subgid
foomatic                modules-load.d       subgid-
fprintd.conf            motd                 subuid
fstab                   mtab                 subuid-
fuse.conf               mtools.conf          sudoers
gai.conf                mysql                sudoers.d
gconf                   nanorc               sysctl.conf
geoclue                 netconfig            sysctl.d
ghostscript             network              systemd
gimp                    NetworkManager       terminfo
glvnd                   networks             thunderbird
GNUstep                 nilfs_cleanerd.conf  timezone
groff                   nsswitch.conf        tmpfiles.d
group                   openal               ucf.conf
group-                  openvpn              udev
grub.d                  opt                  udisks2
gshadow                 os-release           ufw
gshadow-                ostree               UPower
gss                     os-version           usb_modeswitch.conf
gtk-2.0                 pam.conf             usb_modeswitch.d
gtk-3.0                 pam.d                vdpau_wrapper.cfg
hdparm.conf             papersize            vim
host.conf               passwd               vpnc
hostname                passwd-              vulkan
hosts                   pbis                 wgetrc
hosts.allow             perl                 wireshark
hosts.deny              plymouth             wpa_supplicant
hp                      pnm2ppa.conf         X11
ifplugd                 polkit-1             xattr.conf
ImageMagick-6           power                xdg
init.d                  ppp                  xl2tpd

$ ls /etc >> etc.txt
$ ls
a.out  a.txt  etc.txt  main.c

如果我们重定向了两次,在txt文件里会显示两份内容,那么可以修改为单箭头,则只保留最新的。

$ ls /etc > etc.txt

这里我们试一下输入流

编写一个输入的txt文件,内容为6 8

vi input.txt

$ cat input.txt
6
8

执行a.out文件,可以直接读取input.txt的内容从而得到结果

$ ./a.out < input.txt
input the int value i:
input the int value j:
i+j=14

那么对于错误流

先删除所有的.out和.txt文件

$ rm a.out
$ ls
a.txt  etc.txt  input.txt  main.c

$ rm *.txt
$ ls
main.c

修改main.c函数内容,让j=0时会报错

#include <stdio.h>

int main()
{
        printf("input the int value i:\n");
        int i,j;
        scanf("%d",&i);
        printf("input the int value j:\n");
        scanf("%d",&j);
        if(0!=j) {
        printf("%d/%d=%d\n",i,j,i/j);
        }else{
                fprintf(stderr,"j != 0\n");
                return 1;
        }
        return 0;
}

编译,发现j=0的时候输出对应错误信息

$ gcc main.c
$ ./a.out
input the int value i:
8
input the int value j:
4
8/4=2
$ echo $?
0
$ ./a.out
input the int value i:
8
input the int value j:
0
j != 0
$ echo $?
1

将正确结果和错误结果分别导出到txt文件里

$ ./a.out 1>true.txt 2>false.txt
4
0

$ ls
a.out  false.txt  main.c  true.txt

$ cat true.txt
input the int value i:
input the int value j:

$ cat false.txt
j != 0

当然也可以输入,但是我们的input.txt还没有创建,所以会显示如下结果,所以我们可以先创建input.txt文件,就可以正常执行

$ ./a.out 1>true.txt 2>false.txt <input.txt
$ ls
a.out  false.txt  main.c  true.txt
$ cat true.txt
$ cat false.txt
bash: input.txt: 没有那个文件或目录

管道原理及应用

实际就是前一个命令的输出流作为后一个命令的输入流,命令之间用 | 隔开

举个例子

$ ls /etc/
acpi                    initramfs-tools      presage.xml
adduser.conf            inputrc              product-info
adjtime                 insserv              profile
alsa                    insserv.conf         profile.d
alternatives            insserv.conf.d       protocols
apache2                 iproute2             proxychains4.conf
apm                     ipsec.conf           pulse
apparmor.d              ipsec.d              python
appstore.json           ipsec.secrets        python2.7
apt                     issue                python3
bash.bashrc             issue.net            python3.7
bash_completion         kernel               rarfiles.lst
bash_completion.d       kernel-img.conf      rc0.d
bindresvport.blacklist  laptop-mode          rc1.d
binfmt.d                ldap                 rc2.d
bluetooth               ld.so.cache          rc3.d
ca-certificates         ld.so.conf           rc4.d
ca-certificates.conf    ld.so.conf.d         rc5.d
calendar                libaudit.conf        rc6.d
chatscripts             libblockdev          rcS.d
cron.d                  libibverbs.d         rearj.cfg
cron.daily              libnl-3              resolv.conf
cron.hourly             libpaper.d           rmt
cron.monthly            libreoffice          rpc
crontab                 lightdm              rsyslog.conf
cron.weekly             lighttpd             rsyslog.d
cryptsetup-initramfs    live                 samba
crypttab                locale.alias         sane.d
cups                    locale.gen           securetty
dbus-1                  localtime            security
dde-dock                logcheck             selinux
debconf.conf            login.defs           sensors3.conf
debian_version          logrotate.conf       sensors.d
deepin                  logrotate.d          services
deepin-authenticate     lsb-release          shadow
deepin-installer.conf   lscolor-256color     shadow-
deepin-version          lvm                  shells
default                 machine-id           skel
deluser.conf            magic                smartd.conf
dhcp                    magic.mime           smartmontools
dictionaries-common     mailcap              smi.conf
dkms                    mailcap.order        snmp
dpkg                    manpath.config       ssh
emacs                   mdadm                ssl
environment             mime.types           staff-group-for-usr-local
environment.d           mke2fs.conf          strongswan.conf
firefox-esr             modprobe.d           strongswan.d
fonts                   modules              subgid
foomatic                modules-load.d       subgid-
fprintd.conf            motd                 subuid
fstab                   mtab                 subuid-
fuse.conf               mtools.conf          sudoers
gai.conf                mysql                sudoers.d
gconf                   nanorc               sysctl.conf
geoclue                 netconfig            sysctl.d
ghostscript             network              systemd
gimp                    NetworkManager       terminfo
glvnd                   networks             thunderbird
GNUstep                 nilfs_cleanerd.conf  timezone
groff                   nsswitch.conf        tmpfiles.d
group                   openal               ucf.conf
group-                  openvpn              udev
grub.d                  opt                  udisks2
gshadow                 os-release           ufw
gshadow-                ostree               UPower
gss                     os-version           usb_modeswitch.conf
gtk-2.0                 pam.conf             usb_modeswitch.d
gtk-3.0                 pam.d                vdpau_wrapper.cfg
hdparm.conf             papersize            vim
host.conf               passwd               vpnc
hostname                passwd-              vulkan
hosts                   pbis                 wgetrc
hosts.allow             perl                 wireshark
hosts.deny              plymouth             wpa_supplicant
hp                      pnm2ppa.conf         X11
ifplugd                 polkit-1             xattr.conf
ImageMagick-6           power                xdg
init.d                  ppp                  xl2tpd

$ ls /etc/ | grep ab
crontab
crypttab
fstab
mtab

这里就将ls /etc/ 终端的内容传输到grep 并查询其中包含ab的文件

查看当前进程有没有ssh,可以输入,表示linux系统有ssh

$ ps -e | grep ssh
 7515 ?        00:00:00 sshd

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值