您的位置:首页 > 运维架构 > Linux

Linux输入输出重定向(编程:实现写入、展示cat和复制cp的功能)

2016-02-01 17:06 645 查看
就是简单的使用了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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: