实例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);
}
本文介绍了两种不同的文件I/O操作方法,一种是利用read和write等系统调用实现的不带缓冲的I/O操作,另一种是通过标准输入输出流进行的字符读写。这两种方法均可用于终端输入输出或文件内容的复制。

725

被折叠的 条评论
为什么被折叠?



