#include<sys/stat.h> #include<fcntl.h> #include<stdio.h> #include<errno.h> #define BUFFER_SIZE 1024 int main(int argc, char **argv) { int from_fd, to_fd; int bytes_read, bytes_write; char buffer[BUFFER_SIZE]; char *ptr; if(argc != 3) { fprintf(stderr, "Usage:%s fromfile tofile/n/a", argv[0]); exit(1); } /*打開源文件*/ if((from_fd = open(argv[1], O_RDONLY)) == -1) { fprintf(stderr, "Open %s Error:%s/n", argv[1], strerror(errno)); exit(1); } /*建立目的文件*/ if((to_fd = open(argv[2], O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR)) == -1) { fprintf(stderr, "Open %s Error:%s/n", argv[2], strerror(errno)); exit(1); } /*如下代碼是一個經典的拷貝文件的代碼*/ while(bytes_read = read(from_fd, buffer, BUFFER_SIZE)) { /*一個致命錯誤發生了*/ if((bytes_read == -1) && (errno != EINTR)) break; else if(bytes_read > 0) { ptr = buffer; while(bytes_write = write(to_fd, ptr, bytes_read)) { /*一個致命錯誤發生了*/ if((bytes_write == -1) && (errno != EINTR)) break; /*寫完了全部讀的字節*/ else if(bytes_write == bytes_read) break; /*只寫了一部分繼續寫*/ else if(bytes_write > 0) { ptr += bytes_write; bytes_read -= bytes_write; } } /*寫的時候發生的致命錯誤*/ if(bytes_write == -1) break; } } close(from_fd); close(to_fd); exit(0); }