linux cp 原码,APUE习题4.6源代码----实现自己的简易 cp 命令

原题:

编写一个类似 cp 的程序,它复制包含空洞的文件,但不将字节0写到输出文件中去。

源代码:

#include

#include

#include

#include

#include

#define BUF_SIZ 128

int my_cp( const char *file1, const char *file2 )

{

int fd1, fd2;

char buffer[BUF_SIZ];

int res;

int current_position = 0;

int byte_count = 0;

fd1 = open( file1, O_RDWR );

if( -1 == fd1 ) {

perror("open file1 failed");

return -1;

}

fd2 = open( file2, O_RDWR | O_APPEND | O_CREAT | O_TRUNC, 0666 );

if( -1 == fd2 ) {

perror("open file2 failed");

return -1;

}

memset( buffer, '\0', BUF_SIZ );

res = read( fd1, buffer, BUF_SIZ );

if( -1 == res ) {

perror("file1 read error");

return -1;

}

while( 0 != res ) {

byte_count = 0;

for( current_position=0; current_position

if( '\0' != buffer[current_position] ) {

buffer[byte_count] = buffer[current_position];

byte_count++;

}

}

res = write( fd2, buffer, byte_count );

if( -1 == res ) {

perror("file2 write failed");

return -1;

}

memset( buffer, '\0', BUF_SIZ );

res = read( fd1, buffer, BUF_SIZ );

if( -1 == res ) {

perror("file1 read failed");

return -1;

}

}

}

int main(int argc, char *argv[])

{

if( 3 != argc) {

printf("correct usage: ./my_cp file1 file2\n");

exit( EXIT_FAILURE );

}

//产生一个含有空洞的文件 file1

int fd = open( argv[1], O_RDWR | O_CREAT | O_TRUNC, 0666 );

if( -1 == fd ) {

perror("open failed");

exit( EXIT_FAILURE );

}

int res = write( fd, "Hey,man!", strlen("Hey,man!") );

if( -1 == res ) {

perror("file1 write failed");

exit( EXIT_FAILURE );

}

off_t offset = lseek( fd, 10000, SEEK_SET );

if( -1 == offset ) {

perror("lseek failed");

exit( EXIT_FAILURE );

}

res = write( fd, "How are you?", strlen("How are you?") );

if( -1 ==res ) {

perror("file1 write failed");

exit( EXIT_FAILURE );

}

//应用 my_cp 函数拷贝文件

res = my_cp( argv[1], argv[2] );

if( -1 == res ) {

perror("copy failed");

exit( EXIT_FAILURE );

}

exit( EXIT_SUCCESS );

}

运行结果:

[www.linuxidc.com@localhost APUE]$ ./my_cp file1 file2

[www.linuxidc.com@localhost APUE]$ cat file2

Hey,man!How are you?

0f4c176d1fd10711a2240b29a3705156.png

输出文件在本例中为file2,大小为 20 Bytes = strlen("Hey,man!") + strlen("How are you?")。测试通过。

相关链接

0b1331709591d260c1c78e86d0c51c18.png

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值