以Append方式打开文件,设置偏移量无效
1 #include<stdio.h> 2 3 int main() 4 { 5 FILE * fd = fopen("btoo1.c", "ab+"); 6 fpos_t p ; 7 int fp = fgetpos(fd, &p); 8 printf("bef seek: fgetpos = %ld, ftell = %d\n", p, ftell(fd)); 9 fseek(fd, 12, SEEK_SET); 10 fgetpos(fd, &p); 11 printf("bef seek: fgetpos = %ld, ftell = %d\n", p, ftell(fd)); 12 fwrite("*****", 1, 5, fd); 13 fclose(fd); 14 return 0; 15 }
测试代码如上。现象就是这样,原因未知。
解决方案:
设置临时文件,将偏移量前的内容先写到零时文件内,然后删源文件,再将零时文件重命名。
修正:
1 #include<stdio.h>
2 #include<stdlib.h>
3 #include<unistd.h>
4 #include<fcntl.h>
5
6 void main(int argc, char* argv[]){
7 int hd1 = open("kkkk", O_WRONLY);
8 int seek_num = lseek(hd1, 5, SEEK_SET);
9 int write_byte = write("abc", 1, 3, hd1);
10 close(hd1);
11
12 FILE *hd2 = fopen("kkkk", "rb+");
13 seek_num = fseek(hd2, 5, SEEK_SET);
14 write_byte = fwrite("def", 1, 3, hd2);
15 fclose(hd2);
16 }
当需要以写操作并需要seek时,
针对fopen,可以以读方式打开;
针对open,避免使用O_TRUNC模式。