APUE-输入和输出

来源:互联网 发布:windows无法安装usb 编辑:程序博客网 时间:2024/06/07 11:01

stdin stdout

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

// 1-4 将标准输入复制到标准输出#include "apue.h"#define BUFFSIZE 4096int 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);}

这里写图片描述