APUE 第二版 习题3.6
result:
wo de meng
write error!
在csdn论坛上问了这个问题,感谢brookmill的指导!
brookmill在给出答案的同时,还给出了查找问题根源的方法。以下是他的答复:
if (write(fd, buf, n) != n)
{
printf("%d: %s/n", errno, strerror(errno)); // 需要errno.h和string.h
printf("write error!/n");
输出 9: Bad file descriptor
man 2 write里面的解释是
EBADF fd is not a valid file descriptor or is not open for writing.
所以,问题应该是出在open,
$ man 2 open
...... The argument flags must include one of the following access modes: O_RDONLY, O_WRONLY, or O_RDWR.
把open的地方改成 open(argv[1],O_RDWR|O_APPEND)
或者 open(argv[1],O_WRONLY|O_APPEND),
这样就可以写进去了。
小结:
用strerror打印出出错信息真的对调试很有帮助。以后要多加运用。
另外,找出问题根源之后再来翻阅APUE,发现48页open函数一节的确提到了这个问题:即打开或创建文件时,oflag参数中必须指定O_RDONLY,O_WRONLY,O_RDWR三个常量中的一个且只能指定一个。
小结:只看书往往会在理解上有疏漏,通过练手才能发现理解上的偏差或不足。
本文解答了APUE第二版习题3.6的问题,探讨了使用特定标志打开文件进行读写时lseek的功能,并通过代码示例展示了如何正确实现。

547

被折叠的 条评论
为什么被折叠?



