![](/img/trans.png)
[英]Why is data written to a file opened with O_APPEND flag, always written at the end, even with `lseek`?
[英]lseek cause segmentation file in O_APPEND mod
int main(int argc,char* argv[]){
int fd;
off_t foffset;
char* fpath;
char* rbuf;
if(argc!=2){
printf("insert filename as argument!\n");
exit(1);
}
strcpy(fpath,argv[1]);
if( (fd = open(fpath,O_RDWR | O_APPEND)) <0 )
perror("error on open()");
//try to use lseek in file opened in O_APPEND mode
char buf[] = "I'm appending some text!\n";
if( write(fd, buf , sizeof(buf)) <0 )
perror("error on write()");
printf("the write() operation was succesful, let's try to seek and read the file..\n");
foffset = lseek(fd,0L,SEEK_CUR);
if(foffset<0)
perror("error on lseek() :");
close(fd);
return 0;
}
为什么在执行此代码时会产生分段错误? 仅当添加lseek操作时才会发生segFault,否则就可以了。
fpath
是一个狂野的指针,即你在调用strcpy
之前没有为它分配任何存储空间。 但是,由于您只需要一个const char *
作为文件名,您可以进行以下更改。
更改:
strcpy(fpath,argv[1]);
至:
fpath = argv[1];
如果要单独使用fpath
,请更改定义:
char fpath[30];
现在你的strcpy
将按预期工作(尽管你应该检查字符串的长度是否在30以下)。 你可以直接传递argv[1]
来open
,因为你没有做任何其他事情。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.