Copy data from fstream to stringstream with no buffer?

后端 未结 5 1350
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-02-01 19:02

Is there anyway I can transfer data from an fstream (a file) to a stringstream (a stream in the memory)?

Currently, I\'m using a buffer, but th

相关标签:
5条回答
  • 2021-02-01 19:11
    // 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 讨论(0)
  • 2021-02-01 19:14

    In the documentation for ostream, there are several overloads for operator<<. One of them takes a streambuf* and reads all of the streambuffer's contents.

    Here is a sample use (compiled and tested):

    #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);
    }
    
    0 讨论(0)
  • 2021-02-01 19:16
     ifstream f(fName);
     stringstream s;
     if (f) {
         s << f.rdbuf();    
         f.close();
     }
    
    0 讨论(0)
  • 2021-02-01 19:23

    The only way using the C++ standard library is to use a ostrstream instead of stringstream.

    You can construct a ostrstream object with your own char buffer, and it will take ownership of the buffer then (so no more copying is needed).

    Note however, that the strstream header is deprecated (though its still part of C++03, and most likely, it will always be available on most standard library implementations), and you will get into big troubles if you forget to null-terminate the data supplied to the ostrstream.This also applies to the stream operators, e.g: ostrstreamobject << some_data << std::ends; (std::ends nullterminates the data).

    0 讨论(0)
  • 2021-02-01 19:29

    If you're using Poco, this is simply:

    #include <Poco/StreamCopier.h>
    
    ifstream ifs(filename);
    string output;
    Poco::StreamCopier::copyToString(ifs, output);
    
    0 讨论(0)
提交回复
热议问题