fnhdx
fnhdx

Reputation: 331

Is it possible to create an ifstream without a real file

I am using a third party library which needs a ifstream object as input and I have a stringstream object which contains everything they need. Right now, I have to write the content of stringstream to a file and then send a ifstream object to the library. I am wondering if it is possible directly convert stringstream to ifstream in memory so I don't need to write a file on disk? thanks.

Upvotes: 1

Views: 667

Answers (1)

pptaszni
pptaszni

Reputation: 8345

I your library is really accepting std::ifstream instead of std::istream, then I found the following hack:

#include <fstream>
#include <iostream>
#include <sstream>
#include <string>

void foo(std::ifstream& fs)
{
    std::string h;
    fs >> h;
    std::cout << h << std::endl;
}

int main()
{
    std::istringstream s1("hello");
    std::ifstream s2;
    s2.basic_ios<char>::rdbuf(s1.rdbuf());
    foo(s2);
    return 0;
}

I am not sure how safe it is, however, so you might investigate the topic further.

Upvotes: 3

Related Questions