Linux中编程实现cp命令,linux系统编程:自己动手写一个cp命令,linuxcp

linux系统编程:自己动手写一个cp命令,linuxcp

cp命令的基本用法: cp 源文件 目标文件

如果目标文件不存在 就创建, 如果存在就覆盖

实现一个cp命令其实就是读写文件的操作:

对于源文件: 把内容全部读取到缓存中,用到的函数read

对于目标文件: 把缓存中的内容全部写入到目标文件,用到的函数creat

ed00787561524027537ae4fa8e3613cb.gif

128264.html1 /*================================================================2 * Copyright (C) 2018 . All rights reserved.3 *4 * 文件名称:mycp.c5 * 创 建 者:ghostwu(吴华)6 * 创建日期:2018年01月08日7 * 描 述:cp命令编写8 *9 ================================================================*/

10

11 #include

12 #include

13 #include

14 #include

15 #include

16 #include

17

18 #define COPYMODE 0644

19 #define BUF 4096

20

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 charn_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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值