Linux C实现cat命令

cat命令将文件显示在终端上,本质是将文件内容拷贝到标准输出

这里使用read函数时一定是while循环,设置一个4096大小的预读取长度,实际读取长度是返回值size

写函数一定是读多少写多少

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>

# define BUFFER_LEN 4096

void copy(int fdin, int fdout)
{
	char buffer[BUFFER_LEN];
	ssize_t size;
	while(size = read(fdin, buffer, BUFFER_LEN)){
		if(write(fdout,buffer,size)!=size){
			perror("write error");
			exit(1);
		}
	}
	
	if(size<0){
		perror("read error");
  		exit(1);
	}

}



int main(int argc, char *argv[])
{
	int fd_in = STDIN_FILENO;
	int fd_out = STDOUT_FILENO;
        // 批量处理n个输入
	for(int i=1;i<argc;i++){
                // 改变输入文件为读入文件
		fd_in = open(argv[i], O_RDONLY);
		if(fd_in<0){
			perror("open error");
			continue;
		}
		copy(fd_in, fd_out);
		close(fd_in);
	}
	if (argc == 1){
		copy(fd_in, fd_out);
		close(fd_in);
	}

	return 0;

}

猜你喜欢

转载自blog.csdn.net/wwxy1995/article/details/88730317