cp的编写

伪代码:

打开原文件

创建目标文件

读原文件

写入目标文件

非常简单的代码:

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

#define COPMODE 0644
#define BUFFERSIZE 4096

int main(int ac, char* av[]){

    int sourceFd, destinationFd,nChars;
    char buf[BUFFERSIZE];

    if(3 != ac){
        printf("Usage: %s source destination\n",*av);
        exit(1); 
    }
    //    打开原文件
    if(-1 == (sourceFd = open(av[1],O_RDONLY))){
        perror(av[1]);
        exit(1);
    }

//    创建目标文件
    destinationFd = creat(av[2],COPMODE);
    if(-1 == destinationFd){
        perror(av[2]);
        exit(1);
    }


//    读原文件
//    写入目标文件
    while ((nChars= read(sourceFd,buf,BUFFERSIZE)) > 0) {
       if(write(destinationFd,buf,nChars) != nChars){
           perror(av[2]);
           exit(1);
       }
    }
    if(-1 == nChars){
        perror(av[2]);
        exit(1);
    }

    return 0;

}

 

posted @ 2017-04-18 20:44  xwqaz  阅读(294)  评论(0编辑  收藏  举报