apue 习题4.6参考答案

#include "apue.h"
#include "myerr.h"
#include <unistd.h>
#include <fcntl.h>

int 
main(int argc, char *argv[])
{   
    if(argc != 3)
        err_sys("usage: ./EX_4_6.o <src path> <dst path>"); 

    char *src_path = argv[1];
    char *dst_path = argv[2];

    int fd = open(src_path, O_RDWR);
    int fd2 = open(dst_path, O_WRONLY); 

    int n;
    char buf[100] = "1234567890123456789";
    char buf2;  

    /* 给源文件制造空洞,结束后将源文件偏移量设为0 */

    int offset = lseek(fd, 100, SEEK_SET);
    printf("offset of src is %d\n", offset);
    printf("the buf is %s\n", buf);
    if(write(fd, buf, 100) < 0)
        err_sys("write to source file error.");
    lseek(fd, 0, SEEK_SET);

    /* 将源文件内容复制到目标文件 */
    while((n = read(fd, &buf2, 1)) == 1)
    {
        /* 如果读到'\0',则不复制 */
        if(buf2 == '\0')
            continue;
        if(write(fd2, &buf2, 1) != 1)
            err_sys("write error.");
    }

    if(n < 0)
        err_sys("read error.");

    close(fd);
    close(fd2);
    exit(0);
}

  运行此段代码得到的源文件和目标文件的内容如下:
  

/* source */
xxx@xxx:~/Desktop/apue_demo/file_dir$ od -c foo 
0000000   1   2   3   3   4   5   5  \n  \0  \0  \0  \0  \0  \0  \0  \0
0000020  \0  \0  \0  \0  \0  \0  \0  \0  \0  \0  \0  \0  \0  \0  \0  \0
*
0000140  \0  \0  \0  \0   1   2   3   4   5   6   7   8   9   0   1   2
0000160   3   4   5   6   7   8   9  \0  \0  \0  \0  \0  \0  \0  \0  \0
0000200  \0  \0  \0  \0  \0  \0  \0  \0  \0  \0  \0  \0  \0  \0  \0  \0
*
0000300  \0  \0  \0  \0  \0  \0  \0  \0
0000310
/* dest */
xxx@xxx:~/Desktop/apue_demo/file_dir$ od -c bar
0000000   1   2   3   3   4   5   5  \n   1   2   3   4   5   6   7   8
0000020   9   0   1   2   3   4   5   6   7   8   9
0000033
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值