码迷,mamicode.com
首页 > 其他好文 > 详细

文件编程file_copy.c

时间:2014-09-30 23:05:00      阅读:222      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   io   os   ar   文件   sp   div   

//Linux文件编程 — — 系统文件调用中的file_cp.c
//待修改。。。

1
#include <stdio.h> 2 #incldue <sys/stat.h> 3 #include <fcntl.h> 4 #include <errno.h> 5 6 #define BUFFSIZE 1024 7 8 int main(int argc, char *argv[]) 9 { 10 int from_fd, to_fd; 11 int bytes_read, bytes_write; 12 char buffer[BUFFSIZE]; 13 char *ptr; 14 15 if(argc != 3) 16 { 17 fprintf(stderr, "Usage: %s from_file to_file\n", argv[0]); 18 exit(EXIT_FAILURE); 19 } 20 21 //open from_file 22 if((from_fd = open(argv[1], O_RDONLY)) == -1) 23 { 24 fprintf(stderr, "Open %s ERROR:%s\n", argv[1], strerror(errno)); 25 exit(EXIT_FAILURE); 26 } 27 //creat to_file 28 if((to_fd = open(argv[2], O_WRONLY|O_CREAT, S_IRUSR|S_IWUSR)) == -1) 29 { 30    fprintf(stderr, "Open %s ERROR:%s", argv[2], strerror(errno)); 31    exit(EXIT_FAILURE); 32 } 33 34 //经典的拷贝文件代码 35 while(bytes_read = read(from_fd, buffer, BUFFSIZE)) 36 { 37 if((bytes_read == -1) && (errno != EINTR)) break; 38 else if(bytes_read > 0) 39 { 40 ptr = buffer; 41 while(bytes_write = write(to_file, buffer, bytes_read)) 42 { 43 //发生了一个致命的错误 44 if((bytes_write == -1) && (errno != EINTR)) break; 45 //写完了所有读的字节 46 else if(bytes_write == bytes_read) break; 47 //只写了一部分,继续写 48 else if(bytes_write > 0) 49 { 50 ptr += bytes_write; 51 bytes_read -= bytes_write; 52 } 53 } 54 //写的时候发生了错误 55 if(bytes_write == -1) break; 56 } 57 } 58 close(from_fd); 59 close(to_fd); 60 exit(0); 61 }

 

文件编程file_copy.c

标签:style   blog   color   io   os   ar   文件   sp   div   

原文地址:http://www.cnblogs.com/shiddong/p/4002684.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!