Shell命令编写——查看文件的命令cat

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

#define BUFFERSIZE 4096

int main(int ac,char *av[]){
	
	/*创建输入文件的文件描述符*/
	int in_fd;

	/*成功读取的字符串的长度*/
	int n_chars;

	/*字符缓冲区数组*/
	char buf[BUFFERSIZE];


	/*对输入时的参数进行判定*/
	if(ac != 2){
		fprintf(stderr,"usage: %s source destination\n",*av);
		exit(0);
	}
	

	/*打开要查看的文件*/
	if((in_fd=open(av[1],O_RDONLY))==-1){
		printf("Can not open:%s\n",av[1]);
		exit(1);
	}

	/*首先从第一个文件中读取一行数据,返回读取的长度*/
	while((n_chars = read(in_fd,buf,BUFFERSIZE))>0){

	/*按照读取的数据长度将缓冲区的数据输出到标准输出*/
		if(write(1,buf,n_chars)!=n_chars){
			printf("Write error to\n");
			exit(1);
		}
	}


	/*关闭两个文件*/
	if(close(in_fd)==-1){
		printf("Error close files\n");	
		exit(1);
	}
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值