就是简单的使用了read和write函数对标准输入输出文件进行读写,通过在运行程序的时候重定向实现许多功能,先上代码:
#include <unistd.h>
#include <stdio.h>
#include <stdlib.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)
{
error("write error\n");
exit(0);
}
}
if (n < 0)
{
error("read error\n");
exit(0);
}
return 0;
}
- 编辑文本(简单写入):./a >.data
- 展示文本(cat):./a <.data
- 复制文件(cp):./a >.data2 <.data
以下是使用不带缓冲的标准I/O写的- -:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int c;
while ((c = getc(stdin) != EOF)
{
if (putc(c, stdout) == EOF)
{
error("output error\n");
exit(0);
}
}
if (ferror(stdin))
{
error("input error\n");
exit(0);
}
return 0;
}