APUE 习题 4.6, 自己写的程序结果有问题,但找不出原因,求助

2015-12-02 09:20:55 +08:00
 viggox
APUE 习题 4.6 是编写一个类似 cp(1)的程序,负值包含空洞的文件时,不将字节 0 写到输出文件中去,自己写的时候,思路就是循环使用 read 读取原文件到缓冲数组,然后在数组中,抹去'\0', 再将数组内容 write 到新文件中,代码如下:

#include <stdio.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
#include <assert.h>

#define BUFSIZE 1024

int copy(const char *file1, const char *file2){
/*copy contents of file1 to file2, ignore the hole*/
int fd1, fd2, num, i;
int base, probe;
char buf[BUFSIZE];
/*open the source and target files*/
if((fd1 = open(file1, O_RDWR)) == -1){
printf("Error opening %s for copying\n", file1);
return -1;
}
if((fd2 = open(file2, O_RDWR|O_APPEND|O_CREAT|O_TRUNC)) == -1){
printf("Error creating %s to copy\n", file2);
return -1;
}

do{
memset(buf, '\0', BUFSIZE);

if((num = read(fd1, buf, BUFSIZE)) == -1){
printf("Error reading %s for copying\n", file1);
return -1;
}
/*clear all "holes"('\0') in the buf array*/
base =0;
for(i=0; i<num; i++){
if(buf[i] != '\0'){
base++;
}
else{
probe = i+1;
while(probe < num){
if(buf[probe] != '\0'){
buf[base] = buf[probe];
i = probe;
base++;
break;
}
probe++;
}
if(probe == num){
break;
}
}
}
/*write the buf into file2*/
if((num = write(fd2, buf, base)) == -1){
printf("Error writing %s to copy\n", file2);
return -1;
}
}
while(num >0);

close(fd1);
close(fd2);

return 0;
}

int main(int argc, char *argv[]){
char *file1, *file2;

if(argc != 3){
printf("parameter error!\n");
return -1;
}

file1 = argv[1];
file2 = argv[2];
return copy(file1, file2);
}

可是很奇怪的是,编译之后运行,得到的新文件必须使用 sudo 才能打开:
$ ./mycp file.hole newfile
$ cat newfile
cat: newfile: Permission denied
$ sudo cat newfile
abcdefghij

试图删除新文件时,会显示处于“写保护”状态
$ rm newfile
rm: remove write-protected regular file ‘ newfile ’?

而且,复制的时候,也没有赋值完全:
查看原文件:
od -c file.hole
0000000 a b c d e f g h i j \0 \0 \0 \0 \0 \0
0000020 \0 \0 \0 \0 \0 \0 \0 \0 \0 \0 \0 \0 \0 \0 \0 \0
*
0040000 A B C D E F G H I J
0040012

查看新文件:
$ sudo od -c newfile
0000000 a b c d e f g h i j
0000012

可以看到虽然空洞没有被复制,但后面的 ABCDEFGHIJ 同样也没被复制。

实在不清楚上面两个问题原因出在哪里,非科班,初学 linux C/C++ 中,求指教 ^~^
1116 次点击
所在节点    问与答
1 条回复
hei1000
2015-12-02 12:23:53 +08:00
没看,推荐 tlpi

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/240466

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX