第一种:标准IO
#include <stdio.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #define N 32 void mycp(const char * sour,const char * des); int main(int argc, const char *argv[]) {mycp(argv[1],argv[2]);return 0; }void mycp(const char * sour,const char * des) {int fd1 = open(sour,O_RDONLY|O_CREAT,0777);if(0>fd1){perror("fd1");return;}int fd2 = open(des,O_WRONLY|O_CREAT|O_TRUNC,0777);if(0>fd2){perror("fd2");return;}char buf[N];//ssize_t r = read(fd1,buf,N); ssize_t r;while(0<(r=read(fd1,buf,N))){//此处写入的个数write(fd2,buf,r);//r = read(fd1,buf,N); }close(fd1);close(fd2); }
第二种,文件IO
#include <stdio.h> void mycp(const char * sour,const char * des); int main(int argc, const char *argv[]) {if(3 != argc){printf("参数格式不正确,请重新输入\n");return -1;}mycp(argv[1],argv[2]);return 0; }void mycp(const char * sour,const char * des) {FILE *psour = fopen(sour,"r");FILE *pdes = fopen(des,"w");if(NULL == psour || NULL ==pdes){printf("打开文件失败,无法继续\n");return;}int ch = fgetc(psour);while(EOF != ch){fputc(ch,pdes);ch = fgetc(psour);}fclose(psour);fclose(pdes); }