apue 习题4.6参考答案

#include "apue.h"
#include "myerr.h"
#include 
#include 

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

    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

你可能感兴趣的:(c,linux内核)