3

ファイルにデータを追加しようとしていますが、場合によっては、最後から少し戻ってファイルの末尾を上書きしたいことがあります。ただし、どちらseekp( pos )seekp( offset, relative )私には何の効果もありません(負のオフセットを使用する場合の不平を除いて)。間違って使用していますか、それとも壊れていますか?

少し例を次に示します。コンパイラ: gcc バージョン 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;
    }

ここで、0 オフセットを使用してシークすると、ファイルの最後に出力位置が配置され、書き込みが追加されますよね? まあ、それは私には効果がありません(osfは以前は空ではありませんでした):

> ./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::ateios::app(おそらく切り捨てモード) を使用して、 と同じ効果を得ようとしましたios::ate

これがバグレポートのように読める場合は申し訳ありませんが、ここでの使用に何か問題があるかどうかを確認し、seekpそれがコンパイラ固有のものであるかどうかを把握したかったのです。

4

1 に答える 1

4

入力属性と出力属性の両方でファイルを開く必要があります。
次のコードには、通常のエラー処理はありません。テクニックを説明するためのものです。

#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>
于 2010-08-01T08:54:48.543 に答える