您的位置:首页 > 产品设计 > UI/UE

将标准输入复制到标准输出 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);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  io