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
相关产品推荐
相关产品推荐

