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.
Asked
Active
Viewed 391 times
1
-
6I would argue that the library is broken when it insist on a `fstream` instead of accepting a `istream`. Are you sure it has to be a filestream? What library is it? – 463035818_is_not_an_ai Jan 29 '20 at 15:29
-
5Does the function take a `std::ifstream`, or a `std::istream`? the former is bad design, the latter would let you pass the `stringstream` directly to the fucntion. – NathanOliver Jan 29 '20 at 15:38
-
Aside from the concerns about the quality of that library which insists on `std::ifstream` instead of `std::istream`, there might be a work-around possible but I'm not sure about the defails. With a derived buffer, the behavior of streams may be changed (like e.g. here: [SO: How to convert QByteArray to std::istream or std::ifstream?](https://stackoverflow.com/a/52492027/7478597)) and this might work for `std::ifstream` as well. An example for a derived `std::ifstream`, I found in [github: zstr](https://github.com/mateidavid/zstr/blob/master/src/strict_fstream.hpp). – Scheff's Cat Jan 29 '20 at 15:49
-
fwiw I reverted the addition of the tag, because I understand the question as being about avoiding handling files not being about file-handling – 463035818_is_not_an_ai Jan 29 '20 at 15:50
1 Answers
3
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.

pptaszni
- 5,591
- 5
- 27
- 43