Search code examples
c++file-handlingstringstreamofstreamostream

stream to write to a file as well as write to a string variable


I am trying a scenario where in a function it puts data to a file.

func(std::ofstream fileStream, JsonData)
{
parses the Json and does some logic and puts to fil stream
}
std::ofstream fileStream(filename);
func(fileStream, jsonData);
//want a scenario where std::string aa will get values in ofstream.
fileStream.close();

Could anyone please help me out if I can convert the stream data to std::string? I saw that ostream can be converted to stringstream; and that can be move to std::string ; but unable to open a file with ostream.

Please help me out...


Solution

  • Change

    func(std::ofstream fileStream, JsonData)
    {
    parses the Json and does some logic and puts to fil stream
    }
    

    To be

    func(std::ostream& Stream, JsonData)
    {
        //parses the Json and does some logic and puts to fill Stream
    }
    

    And now what you can do is pass a stringstream to the function and have that get filled. Then you can get a string out of it, and pass it's buffer to an ofstream like

    JsonData data;
    std::stringstream ss;
    // populate string stream
    func(ss, data); 
    // get string
    std::string stringifiedData = ss.str();
    // open file
    std::ofstream fileStream(filename);
    // write to file
    fileStream << ss.rdbuf();