fseek的不当文件&QUOT打开工作; A" (追加)模式 [英] fseek does not work when file is opened in "a" (append) mode

查看:150
本文介绍了fseek的不当文件&QUOT打开工作; A" (追加)模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

FILE* f = fopen("rajat", "w");
fputs("sometext", f);
fseek(f, 6, SEEK_SET);
fputs("is a", f);
fclose(f);

成功返回:someteis一个

Successfully returns: "someteis a"

FILE* f = fopen("rajat", "a");
fputs("sometext", f);
fseek(f, 6, SEEK_SET);
fputs("is a", f);
fclose(f);

不工作。返回sometextis一个

Does not work. Returns "sometextis a"

任何想法,为什么?如何解决此,使得第二code输出酷似第一λ

Any ideas why? What is the solution to this, so that the second code outputs exactly like the first?

推荐答案

当你打开追加模式,文件指针返回到文件的每个写之前结束。可以重新定位与 fseek的的指针读数,但只要你把那个叫写入文件中的函数,指针回到文件的末尾。

When you open in append mode, the file pointer is returned to the end of file before every write. You can reposition the pointer with fseek for reading, but as soon as you call a function that writes to the file, the pointer goes back to the end of file.

或者,把它的另一种方式,数据的prevent损失的写指针的位置覆盖的读指针的位置。任何追加后,写指针反弹新 EOF

Or, putting it another way, to prevent loss of data, the position of the "write pointer" overrides the position of the "read pointer". After any append, the write pointer bounces to the new EOF.

此链接引用C标准的适当部分答案。

The answer at this link references the appropriate section of the C standard.

使用W +模式下,如果你想写入文件中的任意地方。现有文件将被覆盖。

Use the "w+" mode if you would like to write to arbitrary places in file. An existing file will be overwritten.

如果您想最初附加到现有的文件,但随后 fseek的任意地方,使用R +其次 fseek的(F,0,SEEK_END)

If you would like to append to an existing file initially, but then fseek to arbitrary place, use "r+" followed by fseek(f, 0, SEEK_END).

这篇关于fseek的不当文件&QUOT打开工作; A" (追加)模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆