文件I/O 2024.8.8

改写cat:

#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[])
{
    if(1==argc)
    {
        return -1;
    }
    for(int i=1;i<argc;i++)
    {
        int fd=open(argv[i],O_RDWR);
        char buf1[10]={0};
        while(1)
        {
            memset(buf1,0,sizeof(buf1));  //将buf1清空

            ssize_t n=read(fd,buf1,sizeof(buf1)-1);

            if(0==n)
            {
                break;
            }
            printf("%s",buf1);

        }
    }
    return 0;
}                                                     

效果如下:

改写scopy:

#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[])
{
    if(argc !=3)
    {
        printf("错误,只要两个参数\n");
        return -1;
    }
    int fd1 = open(argv[1],O_RDWR);
    int fd2 = open(argv[2],O_RDWR);
    char buf1[20]={0};
    while(1)
    {
        memset(buf1,0,sizeof(buf1));  //将buf1清空

        ssize_t n=read(fd1,buf1,sizeof(buf1)-1);

        write(fd2,buf1,strlen(buf1));//将读取的数据写入fd2

        //printf("%s\n",buf1);
        if(0==n)
        {
            break;
        }
    }

    close(fd2);
    return 0;
}                                                            

实现diff命令:

#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[])
{
    if(argc!=3)
	{
		printf("需要两个参数");
		return -1;
	}
	int fd1=open(argv[1],O_RDWR);
	int fd2=open(argv[2],O_RDWR);
	char buf1[10]={0};
	char buf2[10]={0};
	while(1)
	{
		int rd1=read(fd1,buf1,sizeof(buf1)-1);
		int rd2=read(fd2,buf2,sizeof(buf2)-1);
		if(strcmp(buf1,buf2)!=0)
		{
			int fd3=open(argv[1],O_RDWR);
			int fd4=open(argv[2],O_RDWR);
			memset(buf1,0,sizeof(buf1));
			memset(buf1,0,sizeof(buf2));
			while(1)
			{
				memset(buf1,0,sizeof(buf1));
				int rd3=read(fd3,buf1,sizeof(buf1)-1);
				if(0==rd3)
				{
					break;
				}
				printf("%s",buf1);

			}
			while(1)
			{
				memset(buf2,0,sizeof(buf2));
				int rd4=read(fd4,buf2,sizeof(buf2)-1);
				if(0==rd4)
				{
					return 0;
				}
				printf("%s",buf2);

			}                                    
		}
		if(0==rd1 || 0==rd2)
		{
			return 0;
		}
		
		
	}
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值