linux系統編程:cp的另外一種實現方式,linuxcp
之前,這篇文章:linux系統編程:自己動手寫一個cp命令 已經實現過一個版本。
這裡再來一個版本,涉及知識點:
linux系統編程:open常用參數詳解
Linux系統編程:簡單檔案IO操作
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 BUFSIZE21 #define BUFSIZE 102422 #endif23 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