apue 习题4.6参考答案
2017-09-15 11:17
274 查看
#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
相关文章推荐
- 素朴集合论1.4节习题参考答案
- 2008秋-计算机软件基础-第四章习题参考答案 P131 ,习题4,5
- 我的谭浩强版《c++程序设计》习题答案参考(新近添加第六章指针,将继续)
- 计算机程序的构造和解释第一章习题参考答案(DrPacket中编译通过)
- 2008秋-计算机软件基础-第四章习题参考答案 P131 ,习题6之一
- Java 习题2 参考答案及解析(2)
- 习题5.5参考答案,求分段函数的值
- 第十三讲习题参考答案
- 自考本科《计算机网络原理》课后习题参考答案(第一章)
- c++ primer plus第二章习题答案(原创请参考)
- 习题5.6参考答案,switch的练习
- Chapter2-数据类型_课后习题参考答案
- Apue Chapter 8 习题答案
- 第一章 绪论习题参考答案
- 《机器学习(周志华)》 习题9.4参考答案
- Java 习题1 参考答案及解析
- 北大ACM习题参考答案
- 李航《统计学习方法》第4章习题答案参考
- 自考本科《计算机网络原理》课后习题参考答案(第二章)
- Apue Chapter 6 习题答案