APUE-输入和输出

stdin stdout

实验1-4 将标准输入复制到标准输出

// 1-4 将标准输入复制到标准输出
#include "apue.h"
#define BUFFSIZE 4096
int main(void) {
    int n;
    char buf[BUFFSIZE];
    while ( (n = read(STDIN_FILENO, buf, BUFFSIZE)) > 0)
        if (write(STDOUT_FILENO, buf, n) != n)
            err_sys("write error");
    if (n < 0)
        err_sys("read error");
    exit(0);
}
  • 将上述代码写入文件 stdin_stdout_copy.c
  • 编译 stdin_stdout_copy.c
gcc stdin_stdout_copy.c -o stdin_stdout_copy -lapue

这里写图片描述
1. 执行方式一:./stdin_stdout_copy >data

此时标准输入是终端,标准输出重定向到文件data,标准错误也是终端,键入文件结束符(CTRL+D),将终止本次复制。

  1. 执行方式二:./stdin_stdout_copy < data > data2

    会将名为data的文件内容复制到名为data2的文件中,若无data2文件则创建。

实验1-5 用标准I/O将标准输入复制到标准输出

#include "apue.h"
int main(void) {
        int c;
        while ( (c = getc(stdin)) != EOF)
                if (putc(c, stdout) == EOF)
                        err_sys("output error");
        if (ferror(stdin))
                err_sys("input error");
        exit(0);
}
  • 步骤与上述类似

    这里写图片描述

实验1-7 从标准输入命令并执行

#include "apue.h"
#include <sys/wait.h>

int main(void)
{
    char buf[MAXLINE]; /* from apue.h */
    pid_t pid;
    int status;
    printf("%% "); /* print prompt (printf requires %% to print %) */
    while (fgets(buf, MAXLINE, stdin) != NULL) {
        if (buf[strlen(buf) - 1] == '\n')
            buf[strlen(buf) - 1] = 0; /* replace newline with null */
        if ((pid = fork()) < 0) {
            err_sys("fork error");
        } else if (pid == 0) { /* child */
            execlp(buf, buf, (char *)0);
            err_ret("couldn't execute: %s", buf);
            exit(127);
        }
        /* parent */
        if ((pid = waitpid(pid, &status, 0)) < 0)
            err_sys("waitpid error");
        printf("%% ");
    }
    exit(0);
}

这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值