Home > database >  writing buffer to ofstream causes tellp() to point to the end of file
writing buffer to ofstream causes tellp() to point to the end of file

Time:01-02

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

CodePudding user response:

From my comment above.

Documentation for open modes

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.

  • Related