当以O_APPEND选项打开一个文件时,能否使用lseek指定文件偏移量?指定之后,从文件什么地方开始进行写?读操作又是如何?
#include<iostream>
#include<fcntl.h>
#include<unistd.h>
using namespace std;
int main(){
int fd=open("a.c",O_RDWR|O_APPEND);
char buf='m';
if(write(fd,&buf,1)==-1){
cout<<"write error"<<endl;
close(fd);
return 0;
}
off_t cp=lseek(fd,0,SEEK_CUR);
cout<<"CUR POS:"<<cp<<endl;
if(lseek(fd,0,SEEK_SET)==-1){
cout<<"lseek error"<<endl;
close(fd);
return 0;
}
cout<<"new pos:"<<lseek(fd,0,SEEK_CUR)<<endl;
char buf2='p';
write(fd,&buf2,1);
close(fd);
return 0;
}可以看到执行后文件中内容为mp,意思说可以用lseek指定。但是每次写仍旧是写在文件末尾的。
本文通过一个示例程序探讨了在使用O_APPEND标志打开文件时,lseek函数的作用及其对读写操作的影响。实验表明,尽管可以调用lseek改变文件位置指针,但写操作仍会发生在文件末尾。

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



