2024年8月8日 IO系统 cat cp diff实现

1.cat实现

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <unistd.h>


//实现cat命令
int main(int argc, const char *argv[])
{
    char r_buf[1000];

    if(argv<3)
    {
        printf("请输入两个文件夹参数");
        return -1;
    }

    for(int i=1;i<argc;i++)
    {
        memset(r_buf,0,sizeof(r_buf));
        int k=open(argv[i],O_RDWR);
        if(k==-1)
        {
            perror("文件打开失败");
            return-1;
        }
        while(1)
        {
            int r=read(k,r_buf,sizeof(r_buf)-1);
            if(r==0)
            {
                break;
            }
             printf("%s",r_buf);


        }
    }
    close(r);                                      
    return 0;
}   

2.cp命令的实现

#include <stdio.h>                                
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <unistd.h>

int main(int argc, const char *argv[])
{
    if(argc!=3)
    {
        printf("只要求传入两个文件");
    }
    char buf[100];
    int fd1=open(argv[1],O_RDWR);
    if(fd1==-1)
    {
        perror("文件1打开失败");
    }
    int fd2=open(argv[2],O_RDWR | O_CREAT);
    if(fd2==-1)
    {
        perror("文件2打开失败");
    }
    while(1)
    {
        memset(buf,0,sizeof(buf));
        int rd=read(fd1,buf,sizeof(buf));
        if(rd==0)
        {
            break;
        }
        int wr=write(fd2,buf,strlen(buf));
        if(wr==0)
        {
            printf("写入失败");
        }
    }
    close(fd1);
    close(fd2);
    return 0;
}
                                                  
                                                  
                                                  
                                                  

3.实现diff命令

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <unistd.h>


#define N 500

int main(int argc, const char *argv[])
{
    if (argc != 3)
    {
        printf("请输入两个文件名\n");
        return 1;
    }

    int fd1 = open(argv[1], O_RDONLY);
    if (fd1 == -1)
    {
        perror("文件1打开失败");
        return 1;
    }

    int fd2 = open(argv[2], O_RDONLY);
    if (fd2 == -1)
    {
        perror("文件2打开失败");
        close(fd1);
        return 1;
    }

    char buf1[N];
    char buf2[N];
    int read1, read2;

    while(1)
    {
        read1 = read(fd1, buf1, N);
        read2 = read(fd2, buf2, N);
                                                  
        if (read1 != read2)
        {
            printf("不相同\n");
        }
        else
        {
            printf("相同\n");
        }

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值