3

fstreamを使用してファイルを読み取り、テキストの一部を書き換えて残りのファイルを削除するプログラムを作成しようとしています。これは私がやろうとしているコードです

#include<iostream>
#include<fstream>

using namespace std;
int main(int argc, char **argv){
    fstream *binf;
    fstream someFile("t.txt", ios::binary|ios::out|ios::in);
    int i;
    for(i=0;i<3;i++){
        char c;
        someFile.seekg(i);
        someFile.get(c);
        cout<<"c:"<<c<<endl;
    }
    someFile.seekp(i++);
    someFile.put("Y");
    someFile.seekp(i++);
    someFile.put("Y");
    //Delete the rest of the file
    return 0;
}

ファイルを開くための次のフラグに注意してください

ios::in Open for input operations.
ios::out    Open for output operations.
ios::binary Open in binary mode.
ios::ate    Set the initial position at the end of the file. If this flag is not set to any value, the initial position is the beginning of the file.
ios::app    All output operations are performed at the end of the file, appending the content to the current content of the file. This flag can only be used in streams open for output-only operations.
ios::trunc  If the file opened for output operations already existed before, its previous content is deleted and replaced by the new one.

これらの多くの組み合わせを試してみましたが、テキストが見つかるまでファイルを読みたいと思っていることを実行するのに役立つものはありません。必要なテキストが見つかったら、それを上書きして残りのファイルを削除します。そのため、ファイルのサイズを小さいファイルに変更する必要があります。

4

1 に答える 1

2

単一のストリーム オブジェクトでそれを行うことはできません。

可能な解決策:

ファイルを閉じて、truncate 関数を呼び出します。

 #include <unistd.h>
 int ftruncate(int fildes, off_t length);
 int truncate(const char *path, off_t length); 

MS Windows バージョンの truncate は、http://msdn.microsoft.com/en-us//library/dk925tyb.aspx_chsizeを参照してください。

int _chsize( 
   int fd,
   long size 
);

または、ファイルを読み取り専用で開き、読み取り/文字列ストリームに置き換えてから、今回は上書き用に開いたファイルにすべてを置きます。

fstream someFile("t.txt", ios::binary|ios::in);
stringstream ss;
// copy (with replacing) whatever needed from someFile to ss 
someFile.close();
someFile.open("t.txt", ios::binary|ios::out|ios::trunc);
someFile << ss.rdbuf();
someFile.close();
于 2012-10-28T19:23:43.360 に答える