Linux文件操作函数仿写cat命令,diff命令,cp命令

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
int main(int argc, const char *argv[])
{
	printf("参数个数=%d\n",argc);
	if(2 >argc)
	{
		printf("错误,至少需要1个参数\n");
		return -1;
	}

	for(int i=1;i<argc;i++)
	{
		int fd=open(argv[i],O_RDONLY);
		if(-1 == fd)
		{
			//printf("打开%S失败,错误为%S\n",argv[i],strerror(errno));
			perror("打开失败");
			return-1;
		}

		char buf[100]={0};
		while(1)
		{
			memset(buf,0,sizeof(buf));
			int ret=read(fd,buf,sizeof(buf)-1);
			if(0 == ret)
				break;
			printf("%s\n",buf);
		}
		close(fd);
	}


	putchar(10);
	return 0;
}
#include <stdio.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>

int main(int argc, const char *argv[])
{
	if(3 != argc)
	{
		printf("filename error");
		return -1;
	}

	int fd1=open(argv[1],O_RDONLY);
	if(-1 == fd1)
	{
		perror("open fil1e error");
		return -1;
	}
	int fd2=open(argv[2],O_RDONLY);
	if(-1 == fd2)
	{
		perror("open fil2e error");
		return -1;
	}

	//比较文件大小
	int size1=lseek(fd1,0,SEEK_END);
	int size2=lseek(fd2,0,SEEK_END);

	lseek(fd1,0,SEEK_SET);
	lseek(fd2,0,SEEK_SET);

	char buf1[10]={0};
	char buf2[10]={0};

	if(size1 != size2)
	{
		printf("file different\n");
		return -1;
	}
	
	while(1)
	{
		memset(buf1,0,sizeof(buf1));
		int ret1=read(fd1,buf1,sizeof(buf1)-1);	
		memset(buf2,0,sizeof(buf2));
		int ret2=read(fd2,buf2,sizeof(buf2)-1);
		//比较大小
		if(0 != strcmp(buf1,buf2))
		{
			printf("different\n");
			return -1;
		}
		if(0 == ret2)
		{
			printf("file相同\n");
			break;
		}
	}
	
	
	return 0;

	close(fd1);
	close(fd2);
}
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>

int main(int argc, char **argv)

{
	printf("argc=%d\n",argc);
	if(3 != argc)
	{
		printf("错误,ineed two file");
		return -1;
	}

	int fd1=open("./1.txt",O_RDWR);
	if(-1 == fd1)
	{
		perror("创建失败");
		return -1;
	
	}
	int fd2=open(argv[2],O_RDWR | O_CREAT | O_TRUNC,0644);
	if(-1 == fd2)
	{
		printf("创建%s失败,错误为%s\n",argv[2],strerror(errno));
		return -1;
	}
	
	while(1)
	{
		char buf[100]={0};
		memset(buf,0,sizeof(buf));
		int ret=read(fd1,buf,sizeof(buf)-1);
		write(fd2,buf,strlen(buf));
		if(0 == ret)
			break;
	}

	close(fd1);
	close(fd2);
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值