Creating fstream object from a FILE* pointer
Asked Answered
M

3

34

The well known way of creating an fstream object is:

ifstream fobj("myfile.txt");

ie. using a filename.

But I want to create an ifstream object using a file descriptor.

Reason: I want to execute a command using _popen(). _popen() returns the output as a FILE*. So there is a FILE* pointer involved but no filename.

Microchemistry answered 19/5, 2012 at 17:48 Comment(2)
@Joe: Posix file descriptors are yet another thing. Presumably, both C++ iostreams and C I/O are implemented in terms of them on a Posix platform. The present question is more reasonable, though, since both iostreams and C I/O are part of the standard library.Erbe
this is a duplicate of #2746668 given you can use fileno on the FILE* returned from popenPfeffer
E
8

You cannot do that just in standard C++, since iostreams and C I/O are entirely separate and unrelated. You could however write your own iostream that's backed by a C FILE stream. I believe that GCC comes with one such stream class as a library extension.

Alternatively, if all you want is an object-y way of wrapping a C FILE stream, you could use a unique pointer for that purpose.

Erbe answered 19/5, 2012 at 17:51 Comment(3)
Basically I want to read _popen()'s output into a single string. A little research led me to fstream. Please suggest something to that context.Microchemistry
@ahmedtabrez: Just go with std::fread as usual; use an intermediate buffer and append the bytes you read to your result string. Or look into those GCC extensions.Erbe
Please, can we discuss here: chat.stackoverflow.com/rooms/11467/…Microchemistry
M
0

You can try QTextStream.

See in https://doc.qt.io/qt-6/qtextstream.html#QTextStream-2

Mascarenas answered 10/5, 2022 at 7:34 Comment(1)
Did he say he was Qt friendly? Question says NIMBY.Boiling
E
-3

You can create a string, and use fread to read and append to it. It's not clean, but you're working with a C interface.

Something like this should work:

FILE * f = popen(...)
const unsigned N=1024;
string total;
while (true) {
    vector<char> buf[N];
    size_t read = fread((void *)&buf[0], 1, N, f);
    if (read) { total.append(buf.begin(), buf.end()); }
    if (read < N) { break; }
}
pclose(f);
Eats answered 10/10, 2014 at 14:35 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.