C 为什么SEEK_SET标志未按预期工作
我尝试对一个以写模式打开的文件执行lseek(),如下所示。但它并没有像预期的那样发挥作用C 为什么SEEK_SET标志未按预期工作,c,linux,C,Linux,我尝试对一个以写模式打开的文件执行lseek(),如下所示。但它并没有像预期的那样发挥作用 #include <stdio.h> #include <sys/types.h> #include <unistd.h> #include <fcntl.h> main() { int fd = open("/local/sandbox/.C/mytest", O_WRONLY | O_APPEND); if(fd == -1)
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <fcntl.h>
main()
{
int fd = open("/local/sandbox/.C/mytest", O_WRONLY | O_APPEND);
if(fd == -1)
{
printf("\nFailed to opne file in write mode\n");
return -1;
}
lseek(fd, 2, SEEK_SET);
write(fd, "OK", 2);
write(fd, "AAAAAAAA", 3);
close(fd);
}
#包括
#包括
#包括
#包括
main()
{
int fd=open(“/local/sandbox/.C/mytest”,O_WRONLY | O_APPEND);
如果(fd==-1)
{
printf(“\n在写入模式下无法访问opne文件\n”);
返回-1;
}
lseek(fd,2,SEEK_集);
写入(fd,“OK”,2);
书写(fd,“AAAAA”,3);
关闭(fd);
}
“mytest”文件已存在,内容为“你好”。我以为在执行程序后,我的测试将包含“HiOKAAA,你好吗”。但它在结尾处写“OKAAA”。这是因为O_APPEND标志吗?但即使如此,我也在使用lseek()仅将文件偏移量更改为“2”。任何人都可以告诉我失败的原因吗?是的,
O\u APPEND
选项导致此问题。根据POSIX规范:
O_追加
如果已设置,则应在每次写入之前将文件偏移量设置为文件末尾
如果您希望能够写入文件中的任意位置,请不要使用
O_APPEND
模式。是的,这是因为O_APPEND
。这使得它在所有写入之前都会搜索到底。