31

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.

Tabrez Ahmed
  • 2,830
  • 6
  • 31
  • 48
  • 1
    @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. – Kerrek SB May 19 '12 at 17:53
  • this is a duplicate of http://stackoverflow.com/questions/2746168/how-to-construct-a-c-fstream-from-a-posix-file-descriptor given you can use `fileno` on the `FILE*` returned from `popen` – Alnitak Oct 10 '14 at 14:39

3 Answers3

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.

Community
  • 1
  • 1
Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
  • 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. – Tabrez Ahmed May 19 '12 at 18:08
  • 1
    @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. – Kerrek SB May 19 '12 at 18:14
  • Please, can we discuss here: http://chat.stackoverflow.com/rooms/11467/room-for-ahmedtabrez-and-kerrek-sb – Tabrez Ahmed May 19 '12 at 18:20
0

You can try QTextStream.

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

untitled
  • 181
  • 6
-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);
Pablo Alvarez
  • 154
  • 1
  • 5