之前,這篇文章:linux系統編程:自己動手寫一個cp命令 已經實現過一個版本。 這裡再來一個版本,涉及知識點: linux系統編程:open常用參數詳解 Linux系統編程:簡單文件IO操作 1 /* 2 * Copyright (C) 2018 . All rights reserved. 3 ...
之前,這篇文章:linux系統編程:自己動手寫一個cp命令 已經實現過一個版本。
這裡再來一個版本,涉及知識點:

1 /*================================================================ 2 * Copyright (C) 2018 . All rights reserved. 3 * 4 * 文件名稱:cp.c 5 * 創 建 者:ghostwu(吳華) 6 * 創建日期:2018年01月10日 7 * 描 述:用open和write實現cp命令 8 * 9 ================================================================*/ 10 11 #include <stdio.h> 12 #include <sys/types.h> 13 #include <sys/stat.h> 14 #include <fcntl.h> 15 #include <errno.h> 16 #include <stdlib.h> 17 #include <string.h> 18 #include <unistd.h> 19 20 #ifndef BUFSIZE 21 #define BUFSIZE 1024 22 #endif 23 24 25 int main(int argc, char *argv[]) 26 { 27 int input_fd, output_fd, openflags; 28 mode_t fileperms; 29 ssize_t num; 30 31 openflags = O_WRONLY | O_CREAT | O_TRUNC; 32 fileperms = S_IRUSR | S_IWUSR | S_IXUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IXOTH; 33 34 if( argc != 3 || strcmp( argv[1], "--help" ) == 0 ) { 35 printf( "usage:%s old-file new-file\n", argv[0] ); 36 exit( -1 ); 37 } 38 39 //打開源文件 40 input_fd = open( argv[1], O_RDONLY ); 41 if( input_fd < 0 ) { 42 printf( "源文件%s打開失敗\n", argv[1] ); 43 exit( -1 ); 44 } 45 46 //創建目標文件 47 output_fd = open( argv[2], openflags, fileperms ); 48 if( output_fd < 0 ) { 49 printf( "目標文件%s創建失敗\n", argv[2] ); 50 exit( -1 ); 51 } 52 53 char buf[BUFSIZE]; 54 55 //開始讀取源文件的數據,向目標文件拷貝數據 56 while( ( num = read( input_fd, buf, BUFSIZE ) ) > 0 ) { 57 if( write( output_fd, buf, num ) != num ) { 58 printf( "向目標文件%s寫入數據失敗\n", argv[2] ); 59 exit( -1 ); 60 } 61 } 62 63 if( num < 0 ) { 64 printf( "讀取源文件%s數據失敗\n", argv[1] ); 65 exit( -1 ); 66 } 67 68 if( close( input_fd ) < 0 ) { 69 perror( "close input_fd" ); 70 exit( -1 ); 71 } 72 if( close( output_fd ) < 0 ) { 73 perror( "close output_fd" ); 74 exit( -1 ); 75 } 76 77 return 0; 78 }View Code