Get FILE * pointer from C++ stream?

M

Markus Dehmann

Can I get a dumb FILE * pointer from a C++ stream?

#include <iostream>
#include <sstream>

using namespace std;

int main(){
stringstream my_stream;
my_stream << "Hello World!" << endl;
// FILE *p = ???;
}

The reason is that I work with a C library that needs a FILE pointer,
but I am calling it from C++ and want to pass a string, actually. I
cannot use fmemopen, because it is not portable (only GNU).

Thanks
Markus
 
R

Rolf Magnus

Markus said:
Can I get a dumb FILE * pointer from a C++ stream?

What do you mean by "dumb"? Anyway, if you mean a standard [io]fstream,
the answer is no, you can't. Most won't even use FILE* internally, but
rather the OS facitily blow that is also used by FILE*.
#include <iostream>
#include <sstream>

using namespace std;

int main(){
stringstream my_stream;
my_stream << "Hello World!" << endl;
// FILE *p = ???;
}

Huh? How is a stringstream connected to a FILE*? A stringstream writes
to or reads from a string, not a file.
 
J

Jonathan Turkanis

Markus Dehmann said:
Can I get a dumb FILE * pointer from a C++ stream?

#include <iostream>
#include <sstream>

using namespace std;

int main(){
stringstream my_stream;
my_stream << "Hello World!" << endl;
// FILE *p = ???;
}

Unfortunately, cstdio is not extensible the way C++ iostreams are. You
can't cook up a FILE to represent an arbitrary data source/sink.
The reason is that I work with a C library that needs a FILE pointer,
but I am calling it from C++ and want to pass a string, actually. I
cannot use fmemopen, because it is not portable (only GNU).

Write the string to a temporary file. This may be inefficient, but
there may be no other way.

Jonatan
 
A

Andrew Koenig

Can I get a dumb FILE * pointer from a C++ stream?

Only if your C++ implementation happens to work that way. There is no
guarantee that a C++ stream will be implemented in terms of a C FILE pointer
at all, let alone that there is a way to discover it.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,262
Messages
2,571,059
Members
48,769
Latest member
Clifft

Latest Threads

Top