【发布时间】:2014-06-19 00:11:43
【问题描述】:
我尝试对以写入模式打开的文件执行 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)
{
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);
}
'mytest' 文件已经存在,内容为“嗨,你好吗”。我以为在执行程序后,我的测试将包含“HiOKAAA,你好吗”。但它最后写的是“OKAAA”。是因为 O_APPEND 标志吗?但即使是,我正在使用 lseek() 来更改文件偏移量仅为“2”。谁能告诉我为什么它失败了?
【问题讨论】:
-
是的,因为
O_APPEND。这使得它在所有写入之前寻找到最后。