《apue 习题3.6》
3.6 如果使用追加标志打开一个文件以便读、写,能否仍用lseek在任一位置开始读?能否用lseek更新文件中任一部分的数据?
#include "apue.h"
#include "fcntl.h"
#include "unistd.h"
int main(void)
{
int fd=open("test",O_RDWR | O_APPEND);(此处一开始使用了 逻辑与,导致结果莫名其妙)
// 打开成功,返回文件描述符
if (fd)
{
printf("设置偏移位置为距离文件开始位置10\n");
off_t off = lseek(fd,10,SEEK_SET);
//如果成功,lseek返回新的文件的偏移量,否则返回-1
if(off!=-1)
{
printf("偏移成功,偏移位置为%d\n",off);
char text[5];
int readsize=read(fd,text,5);
//read 读取成功返回读取的字节数。
if(readsize<0)
{
printf("读取失败\n");
}
else
{
printf("读取的内容为: %s\n",text);
}
char *writechar=" add some things ";
int writesize=write(fd,writechar,17);
// write返回成功写入的字数,否则失败
if(17==writesize)
{
printf("似乎写入成功\n");
}
else
{
printf("写入失败!\n");
}
}
else
{
printf("偏移失败\n");
}
close(fd);
}
exit(0);
}
在当前文件夹下有一个test文件,文件内容为
This is a good test.
运行程序的结果为
设置偏移位置为距离文件开始位置10
偏移成功,偏移位置为10
读取的内容为: good
似乎写入成功
文件内容跟变为如下
This is a good test.
add some things
结论
可以在做任意位置的偏移和读取,但是写入只可以在文件末尾加入,答案和参考大难相一致。