C编程fwrite跳转到文件末尾

DSn*_*net 3 c c++ fseek fwrite ftell

我正在写一个C模块,我遇到了一个我以前从未见过的有趣问题.

// Many other operations before this point
fseek(samples_file, 0, SEEK_SET);
printf("ftell A1 %llu\n", ftell(samples_file));
count = fwrite(channel_buffer+chan_type.size*set_index, 1, chan_type.size, samples_file);
printf("count %llu\n", count);
printf("ftell A2 %llu\n", ftell(samples_file));
// Many more operations to come after this point
Run Code Online (Sandbox Code Playgroud)

当我运行模块时,我得到如下打印输出:

ftell A1 0
count 8
ftell A2 6018
Run Code Online (Sandbox Code Playgroud)

我已将文件指针设置为文件的开头.当我写一些数据时,它应该在我寻找的位置写出数据,然后用写入的字节数增加文件位置(在本例中为8).然而,当我做一个ftell时,似乎该位置突然跳到6018(恰好是文件的原始大小加上8).

为什么会发生这种情况,如何防止这种行为?

NPE*_*NPE 5

听起来这个文件已经在附加模式下打开了.检查"a"第二个参数中是否存在fopen().

  • 你在寻找`"r +"`.看看手册页或一本好的C书 - 所有有效模式都将在那里拼写出来. (2认同)