Use c++ streams with legacy c code

solin edited this page Dec 28, 2010 · 1 revision

One should use C++ streams for handling files and input/output (like mesh reading). However, some code (like the old C++ parser) needs the legacy C "FILE" struct and it doesn't work with C++ streams. Here is how to support such code:

std::string read_file(std::istream &is)
{
   std::ostringstream s;
   s << is.rdbuf();
   return s.str();
}

std::string mesh_str = read_file(is);
FILE* f = fmemopen((void *) (mesh_str.c_str()), mesh_str.length(), "r");
if (f == NULL) error("Could not create the read buffer");
mesh_parser_init(f, filename);

This took me quite some time to figure out, I was googling phrases like "C++ streams with FILE", or "emulating FILE struct in C++" and nothing came up. So I am posting here, so that it can be googled out later.