使用C標準庫函數/Linux系統調用實現copy指令

#include<fcntl.h>
#include<stdio.h>
#include<unistd.h>
#include<string.h>

int main(int argc, char *argv[]){

    int srcfd, desfd;
    int count;
    char srcPath[50] = "./";
    char desPath[50] = "./";
    char buf[300];    

    if(argc != 3){
        printf("Usage : %s <source> <destination>\n", argv[0]);
        return 1;
    }

    strcat(srcPath, argv[1]);
    strcat(desPath, argv[2]);

    printf("%s\n", srcPath);
    printf("%s\n", desPath);rm

    srcfd = open(srcPath, O_RDONLY);
    if(srcfd < 0){
        printf("%s open error, exit!\n", argv[1]);
        return 1;
    }
    desfd = open(desPath, O_CREAT | O_RDWR, 0666);
    if(desfd < 0){
        printf("%s open error, exit!\n", argv[2]);
        return 1;
    }

    while(count = read(srcfd, buf, 256)){
        write(desfd, buf, count);
    }

    close(srcfd);
    close(desfd);
    
    return 0;
}

在這裏插入圖片描述

#include<stdlib.h>
#include<stdio.h>
#include<string.h>

int main(int argc, char *argv[]){

    FILE *srcfd, *desfd;
    int count;
    char srcPath[50] = "./";
    char desPath[50] = "./";
    char buf[300];    

    if(argc != 3){
        printf("Usage : %s <source> <destination>\n", argv[0]);
        return 1;
    }

    strcat(srcPath, argv[1]);
    strcat(desPath, argv[2]);

    

    srcfd = fopen(srcPath, "r+");
    if(srcfd == NULL){
        printf("%s open error, exit!\n", argv[1]);
        return 1;
    }
    desfd = fopen(desPath, "w+");
    if(desfd < 0){
        printf("%s open error, exit!\n", argv[2]);
        return 1;
    }

    printf("%s\n", srcPath);
    printf("%s\n", desPath);

    while(count = fread(buf, 1, 256, srcfd)){
        buf[count] = '\0';
        fwrite(buf, 1, count, desfd);
    }

    fclose(srcfd);
    fclose(desfd);
    
    return 0;
}

在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章