26

fstream(ファイル)からstringstream(メモリ内のストリーム)にデータを転送できる方法はありますか?

現在、私はバッファを使用していますが、データをバッファにコピーし、次にバッファを文字列ストリームにコピーする必要があるため、これには2倍のメモリが必要です。バッファを削除するまで、データはメモリに複製されます。

std::fstream fWrite(fName,std::ios::binary | std::ios::in | std::ios::out);  
    fWrite.seekg(0,std::ios::end); //Seek to the end  
    int fLen = fWrite.tellg(); //Get length of file  
    fWrite.seekg(0,std::ios::beg); //Seek back to beginning  
    char* fileBuffer = new char[fLen];  
    fWrite.read(fileBuffer,fLen);  
    Write(fileBuffer,fLen); //This writes the buffer to the stringstream  
    delete fileBuffer;`

中間バッファを使用せずにファイル全体を文字列ストリームに書き込む方法を知っている人はいますか?

4

5 に答える 5

34
 ifstream f(fName);
 stringstream s;
 if (f) {
     s << f.rdbuf();    
     f.close();
 }
于 2010-10-31T19:19:39.510 に答える
31
// need to include <algorithm> and <iterator>, and of course <fstream> and <sstream>
ifstream fin("input.txt");
ostringstream sout;
copy(istreambuf_iterator<char>(fin),
     istreambuf_iterator<char>(),
     ostreambuf_iterator<char>(sout));
于 2010-10-31T19:09:24.350 に答える
7

のドキュメントには、のオーバーロードostreamがいくつかあります。そのうちの 1 つは を取り、ストリーム バッファの内容をすべて読み取ります。operator<<streambuf*

使用例を次に示します (コンパイルおよびテスト済み)。

#include <exception>
#include <iostream>
#include <fstream>
#include <sstream>

int main ( int, char ** )
try
{
        // Will hold file contents.
    std::stringstream contents;

        // Open the file for the shortest time possible.
    { std::ifstream file("/path/to/file", std::ios::binary);

            // Make sure we have something to read.
        if ( !file.is_open() ) {
            throw (std::exception("Could not open file."));
        }

            // Copy contents "as efficiently as possible".
        contents << file.rdbuf();
    }

        // Do something "useful" with the file contents.
    std::cout << contents.rdbuf();
}
catch ( const std::exception& error )
{
    std::cerr << error.what() << std::endl;
    return (EXIT_FAILURE);
}
于 2010-10-31T19:31:03.380 に答える
1

C++ 標準ライブラリを使用する唯一の方法は、 のostrstream代わりに a を使用することですstringstream

独自の char バッファーを使用してオブジェクトを作成すると、そのostrstreamオブジェクトはバッファーの所有権を取得します (したがって、これ以上コピーする必要はありません)。

ただし、strstreamヘッダーは推奨されていないことに注意してください (ただし、C++03 の一部であり、ほとんどの標準ライブラリの実装で常に使用できる可能性が高いです)。 ostrstream に提供されるデータ。これは、ストリーム オペレータにも適用されostrstreamobject << some_data << std::ends;ますstd::ends

于 2010-10-31T19:30:03.270 に答える
0

Pocoを使用している場合、これは単純です:

#include <Poco/StreamCopier.h>

ifstream ifs(filename);
string output;
Poco::StreamCopier::copyToString(ifs, output);
于 2021-01-28T15:23:40.827 に答える