首页 文章

将数据从fstream复制到stringstream而没有缓冲区?

提问于
浏览
19

无论如何我可以将数据从 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;`

有没有人知道如何在不使用inbetween缓冲区的情况下将整个文件写入字符串流?

4 回答

  • 1
    // 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));
    
  • 6
    ifstream f(fName);
     stringstream s;
     if (f) {
         s << f.rdbuf();    
         f.close();
     }
    
  • 25

    ostream 的文档中,有several overloads for operator<< . 其中一个需要 streambuf* 并读取所有streambuffer的内容 .

    这是一个示例用法(编译和测试):

    #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);
    }
    
  • 23

    使用C标准库的唯一方法是使用 ostrstream 而不是 stringstream .

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

    但请注意, strstream 标头已被弃用(尽管它仍然是C 03的一部分,并且很可能在大多数标准库实现中始终可用),如果您忘记空终止数据,您将遇到大麻烦提供给ostrstream . 这也适用于流操作符,例如: ostrstreamobject << some_data << std::ends;std::ends null终止数据) .

相关问题