标签:
copy.c:
#include <stdio.h> #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <string.h> //a.out src.txt dest.txt //argv[0] argv[1] argv[2] int main(int argc,char *argv[]) { char src[20] = {0}; char dest[20] = {0}; int fdr; int fdw; int ret; char buf[1024] = {0}; if(argc != 3){ printf("Usage: %s src.txt dest.txt\n",argv[0]); return -1; } strcpy(src,argv[1]); strcpy(dest,argv[2]); /*1.以的方式打开源文件src.txt*/ fdr = open(src,O_RDONLY); if(fdr < 0){ perror("open"); return -1; } /*2.以写的方式打开目标文件 dest.txt ,如果不存在,则创建*/ fdw = open(dest,O_WRONLY | O_CREAT,0755); if(fdw < 0){ perror("open"); return -1; } /*3.把src文件的指针移动到文件头*/ lseek(fdr,0,SEEK_SET); /*3.循环的读取src.txt ,直到结束*/ while(1) { memset(buf,0,sizeof(buf)); //清零 ret = read(fdr,buf,sizeof(buf)-1); if(ret > 0){ /*4.把读到的内容写入到 dest.txt*/ write(fdw,buf,ret); }else if(0 == ret){ /*读取结束*/ printf("read over!\n"); break; }else{ perror("read"); break; } } /*5.关闭*/ close(fdr); close(fdw); return 0; }
标签:
原文地址:http://www.cnblogs.com/yihujiu/p/5520953.html