Linux操作系统下,通过系统调用和库函数分别实现对文件的拷贝

  • 通过系统调用实现 file.copy
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>

int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        printf("usage : ./copy filename1 filename2\n");
    }

    char buffer[1024] = {0};

    int fd1 = open(argv[1], O_RDWR);/*读写方式打开文件1*/
    if (-1 == fd1)                  /*出错判断*/
    {
        perror("open1");
        return 1;
    }

    int fd2 = open(argv[2], O_RDWR | O_CREAT, S_IRWXU);/*创建新文件并以读写方式打开*/
    if (-1 == fd2)
    {
        perror("open2");
        return 2;
    }

    int count = 0;
    while (count = read(fd1, buffer, 1024))
    {
        if (-1 == count)
        {
            perror("read1");
            close(fd1);
            close(fd2);
            return 3;
        }

        int coun2 = write(fd2, buffer, count);
        if (-1 == count)
        {
            perror("write1");
            close(fd1);
            close(fd2);
            return 4;
        }
        memset(buffer, 0, 1024);     /*清空数组*/
    }
    close(fd1);
    close(fd2);

    return 0;
}

 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 通过库函数实现 file.copy
#include <stdio.h>
#include <string.h>

int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        printf("usage : ./copy filename1 filename2\n");
    }

    char buffer[1024] = {0};

    FILE *file1 = fopen(argv[1], "r+");
    if (NULL == file1)
    {
        perror("fopen");
        return 1;
    }

    FILE *file2 = fopen(argv[2], "w+");
    if (NULL == file2)
    {
        perror("fopen");
        return 2;
    }

    int count = 0;
    count = fread(buffer, sizeof(char), 1024, file1);
    if(0 == count)                   /*出错判断*/
    {
        perror("fread");
        fclose(file1);
        fclose(file2);
        return 3;
    }
    fseek(file1, 0, SEEK_SET);    /*从头再进行读写*/

    while (count = fread(buffer, sizeof(char), 1024, file1))
    {
        int count2 = fwrite(buffer, sizeof(char), count, file2);
        if (count2 == 0)
        {
            perror("fwrite");
            fclose(file2);
            fclose(file1);
            return 4;
        }
        memset(buffer, 0, 1024); 
    }

    fclose(file1);
    fclose(file2);

    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值