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

来源:互联网 发布:淘宝确认收货前退货 编辑:程序博客网 时间:2024/05/16 23:47
  • 通过系统调用实现 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;}
  • 通过库函数实现 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;}
阅读全文
0 0
原创粉丝点击