打电话后
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(); //will be 321
_f.write(buff, 100);
_f.tellp(); //somehow is equal to 1024*512 instead of 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);
否则
documentation
说
“正在创建文件。如果文件已经存在,则使用旧版本
被删除。"