linux系統編程:自己動手寫一個cp命令,linuxcp

來源:互聯網
上載者:User

linux系統編程:自己動手寫一個cp命令,linuxcp

cp命令的基本用法: cp 源檔案 目標檔案

如果目標檔案不存在 就建立, 如果存在就覆蓋

實現一個cp命令其實就是讀寫檔案的操作:

對於源檔案: 把內容全部讀取到緩衝中,用到的函數read

對於目標檔案: 把緩衝中的內容全部寫入到目標檔案,用到的函數creat

1 /*================================================================ 2 * Copyright (C) 2018 . All rights reserved. 3 * 4 * 檔案名稱:mycp.c 5 * 創 建 者:ghostwu(吳華) 6 * 建立日期:2018年01月08日 7 * 描 述:cp命令編寫 8 * 9 ================================================================*/10 11 #include <stdio.h>12 #include <stdlib.h>13 #include <sys/types.h>14 #include <sys/stat.h>15 #include <fcntl.h>16 #include <unistd.h>17 18 #define COPYMODE 064419 #define BUF 409620 21 int main(int argc, char *argv[])22 {23 if ( argc != 3 ){24 printf( "usage:%s source destination\n", argv[0] );25 exit( -1 );26 }27 28 int in_fd = -1, out_fd = -1;29 30 if( ( in_fd = open( argv[1], O_RDONLY ) ) == -1 ) {31 perror( "file open" );32 exit( -1 );33 }34 35 if ( ( out_fd = creat( argv[2], COPYMODE ) ) == -1 ) {36 perror( "file copy" );37 exit( -1 );38 }39 40 char n_chars[BUF];41 int len = 0;42 43 while( ( len = read( in_fd, n_chars, sizeof( n_chars ) ) ) > 0 ) {44 if ( write( out_fd, n_chars, len ) != len ) {45 printf( "檔案:%s發生copy錯誤\n", argv[2] );46 exit( -1 );47 }48 }49 if( len == -1 ) {50 printf( "讀取%s檔案錯誤\n", argv[1] );51 exit( -1 );52 }53 54 if( close( in_fd ) == -1 ) {55 printf( "檔案%s關閉失敗\n", argv[1] );56 exit( -1 );57 }58 if( close( out_fd ) == -1 ) {59 printf( "檔案%s關閉失敗\n", argv[2] );60 exit( -1 );61 }62 63 return 0;64 }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.