linux系統編程:cp的另外一種實現方式,linuxcp

來源:互聯網
上載者:User

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

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.