2010-10-31 66 views
15

反正我可以从一个fstream(文件)(在内存中的数据流)传输数据到stringstream将数据从fstream复制到没有缓冲区的串流中?

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

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;` 

有谁知道我怎么能写一个整个文件到一个stringstream而不使用inbetween缓冲区?

+0

有什么意义?您是否在尝试提高吞吐量?在这种情况下,你可能需要抛弃'fstream',iostreams很慢。你想减少你的内存占用?一次读取文件而不是一次读取文件可以帮助解决这个问题。 – 2010-10-31 19:17:47

回答

25
// 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)); 
+0

这仍然将文件读入'ifstream'缓冲区。 – 2010-10-31 19:11:20

+0

它比原始代码少一个缓冲区。 – 2010-10-31 19:15:50

+0

@Charles - 尽管如此,我认为这是他的意图。他不想分配新的char数组。他想直接从fstream对象读取到stringstream对象。 – 2010-10-31 19:17:15

20
ifstream f(fName); 
stringstream s; 
if (f) { 
    s << f.rdbuf();  
    f.close(); 
} 
1

使用C++标准库的唯一方法是使用的ostrstream代替stringstream

您可以构建一个ostrstream对象与自己的字符缓冲区,这将需要缓冲区的所有权,然后(所以不需要更多的复制)。

但是请注意,strstream标头已被弃用(虽然它仍然是C++ 03的一部分,并且很可能它在大多数标准库实现中始终可用),并且如果您忘记了,则会遇到大麻烦到空终止提供给ostrstream.This数据也适用于该流的运营商,例如:ostrstreamobject << some_data << std::ends;std::ends nullterminates中的数据)。

7

在为ostream的文档,有several overloads for 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); 
} 
相关问题