How to resume adding data to a file at a specific position? (std :: ostream, streampos, tellp / seekp)

I'm trying to add some data to a file, but in some cases I want to skip a bit from the end to overwrite the end of the file. However, neither seekp( pos ), nor seekp( offset, relative )has any effect for me (except for the complaint when using a negative bias). Am I using them incorrectly or are they broken?

The following is a small example. Compiler: gcc version 4.4.4 (Debian 4.4.4-6)

    #include <fstream>
    #include <sstream>
    #include <boost/date_time/posix_time/posix_time.hpp>
    using namespace std;
    using namespace boost::posix_time;

    int main(int nargs, char** pargs){
    if( nargs < 2 || nargs > 3 ){
     cerr<<"Usage: "<<pargs[0]<<" file [pos]"<<endl;
     return 1;
 }

 const char* fname = pargs[1];
 ofstream f( fname, ios::binary|ios::out|ios::ate );
 if( !f.good() ){
     cerr<<"Unable to open file!"<<endl;
     return 1;
 }

 if( nargs == 3 ){
     istringstream offss(pargs[2]);
     streamoff off;
     offss >> off;
     cout <<"Seeking to: "<<off<<endl;
     f.seekp( off, ios_base::end ); // using beg or cur instead doesn't help, nor does: seekp( off )
     if( f.fail() ){
  cerr<<"Unable to seek!"<<endl;
  f.clear(); // clear error flags
     }
 }

 f<<"[appending some data at "<<second_clock::local_time()<<"]\n";

 return 0;
    }

Now, if I'm looking to use offset 0, it should put the output position at the end of the file, and the records should be added, right? Well, this has no effect for me (osf was not empty before):

> ./ostream_app_pos osf 0
Seeking to: 0
> cat osf
[appending some data at 2010-Jul-21 11:16:16]

ios::app. , neg/pos , ( gcc doc):

ios:: app .

ios::ate, ios::app ( ), , ios::ate.

, , , -, , seekp , .

+3
1

.
, .

#include <iostream>
#include <fstream>

int main()
{
    const char *szFname = "c:\\tmp\\tmp.txt";
    std::fstream fs(szFname, 
                    std::fstream::binary | 
                    std::fstream::in     | 
                    std::fstream::out);
    fs.seekp(13, std::fstream::beg);
    fs << "123456789";

    return 0;
}

=============================================== =

C:\Dvl\Tmp>type c:\tmp\tmp.txt
abdcefghijklmnopqrstuvwxyz
C:\Dvl\Tmp>Test.exe
C:\Dvl\Tmp>type c:\tmp\tmp.txt
abdcefghijklm123456789wxyz
C:\Dvl\Tmp>
+3

Source: https://habr.com/ru/post/1755699/


All Articles