将标准输入复制到标准输出 APUE-1.5
2017-03-15 18:36
417 查看
实例1
函数open, read, write, lseek 以及close 提供了不带缓冲的I/O, 这些函数都使用文件描述符.#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #define BUFFSIZE 4096 int main(void) { FILE *fp = NULL; int n; char buf[BUFFSIZE]; while ((n = read(STDIN_FILENO, buf, BUFFSIZE)) > 0) { if (write(STDOUT_FILENO, buf, n) != n) { printf("write error"); } } if (n < 0) { printf("read error"); } exit(0); }
注意:编译上面的程序的时候遇到一个错误,就是在 while() 这一行多加一个分号”;”如下:
while(); { if () }
但是gcc编译器可以编译可通过,但是输出有问题, 但是输出没有出来.
执行方式:
./a.out (直接在终端输入输出)
./a.out > data (在终端输入输出到文件data, 若文件data不存在shell会自动生成)
./a.out < infile > outfile (将文件名为infile文件内容复制到文件名outfile的文件中)
实例2
实例2 和实例1 都能达到同样的效果,执行方式也是三种都可以,但是里面用的函数不一样而已.#include <stdio.h> #include <stdlib.h> int main(void) { int c; while ((c = getc(stdin)) != EOF) { if (putc(c, stdout) == EOF) { perror("output error"); } } if (ferror(stdin)) { perror("input error"); } exit(0); }
相关文章推荐
- APUE 1-4用标准将标准输入复制到标准输出
- APUE 1-5用标准I/O将标准输入复制到标准输出
- APUE-1.2 将标准输入复制到标准输出(read(),write())
- APUE-1.3 用标准I/O将标准输入复制到标准输出
- 将标准输入复制到标准输出
- 第一章 用标准I/O函数将标准输入复制到标准输出 1-3
- 1.3 用标准I/O将标准输入复制到标准输出
- APUE 3-5 将标准输入复制到标准输出
- 3.3 将标准输入复制到标准输出
- 笔记1-2: 将标准输入复制到标准输出
- 笔记1-2: 将标准输入复制到标准输出
- UNIX环境高级编程1-3用标准I/O将标准输入复制到标准输出
- 第一章 将标准输入复制到标准输出 1-2
- 1.2 将标准输入复制到标准输出
- 将标准输入复制到标准输出
- 从标准输入复制到标准输出并打印行号
- UNIX环境高级编程程序1-2将标准输入复制到标准输出
- 使用标准输入&&标准输出,进行文件复制
- 将标准输入复制到标准输出
- 程序3-3 将标准输入复制到标准输出