Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
376 views
in Technique[技术] by (71.8m points)

c++ - fseek does not work when file is opened in "a" (append) mode

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

Successfully returns: "someteis a"

But

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

Does not work. Returns "sometextis a"

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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.

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

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

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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...