Reputation: 1370
After calling seekp()
to the middle of file, then writing my buffer, the file-pointer teleports to the end of file.
My code is more complex but essentially comes down to the following:
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
What might be causing this behavior? It occurs only in one specific place of my code. Other invocations of this code from other places work ok and don't teleport the pointer that far away.
I'm using C++14
Edit:
Following the below answer, I had to use std::ios::ate
not std::ios::app
.
However, I discovered that my file started to be re-created from scratch even though I'm not specifying std::ios::trunc
.
I had to pass in additional flag in
to make sure the file contents are preserved:
auto flags = std::ios::ate | std::ios::in | std::ios::out | std::ios::binary; _f.open("myFile.exten", flags);
otherwise documentation says "Creating a file. If the file already exists, the old version is deleted."
Upvotes: 0
Views: 128
Reputation: 13552
From my comment above.
app: seek to the end of stream before each write
Thus :
_f.write(buff, 100);
…triggers a seek to the end of the file before writing.
Upvotes: 4