You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++ ofstream调用seekp后写入,文件指针跳至末尾的原因排查

问题:调用seekp()定位后写入,文件指针跳至文件末尾

调用seekp()将文件指针定位到文件中间后写入缓冲区,文件指针却跳至文件末尾。

我的代码较为复杂,但核心逻辑如下:

std::lock_guard<std::mutex> lckFile(_mu_fileAccess);

const char* buff = new const char[200];
int preallocSize = 1024*512;

_f.open(path_file_with_exten,  std::ios::app | std::ios::binary );
if(!_f){ 
  delete[] buff;
  return; 
}
std::experimental::filesystem::resize_file(path_with_exten, preallocSize);
_f.seekp(321, std::ios_base::beg);
int64_t currPos = _f.tellp(); //结果为321
_f.write(buff, 100);
_f.tellp(); //结果竟等于1024*512而非321+100

该行为的原因是什么?此问题仅在代码的某一处出现,其他位置调用该代码均正常,不会出现指针大幅偏移的情况。

我使用的是C++14标准。


编辑补充:

根据相关建议,需要使用std::ios::ate而非std::ios::app。但发现文件会被重新创建,即便未指定std::ios::trunc。

必须添加in标志以确保文件内容被保留:

auto flags = std::ios::ate | std::ios::in | std::ios::out | std::ios::binary; _f.open("myFile.exten", flags);

否则根据官方文档说明:

创建文件。若文件已存在,则删除旧版本。

内容的提问来源于stack exchange,提问作者Kari

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 07:50:26