26

无论如何我可以将数据从fstream(文件)传输到stringstream(内存中的流)吗?

目前,我正在使用缓冲区,但这需要双倍内存,因为您需要将数据复制到缓冲区,然后将缓冲区复制到字符串流,直到您删除缓冲区,数据才会在内存中重复。

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,有几个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++ 标准库的唯一方法是使用 aostrstream而不是stringstream.

您可以使用自己的 char 缓冲区构造一个ostrstream对象,然后它将获得缓冲区的所有权(因此不需要更多的复制)。

但是请注意,strstream标头已被弃用(尽管它仍然是 C++03 的一部分,并且很可能在大多数标准库实现中始终可用),如果您忘记空终止提供给 ostrstream 的数据。这也适用于流运算符,例如:(ostrstreamobject << some_data << std::ends;nullstd::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 回答