In Unix, if you have a file descriptor (e.g. from a socket, pipe, or inherited from your parent process), you can open a buffered I/O FILE* stream on it with fdopen(3).
Is there an equivalent on Windows for HANDLEs? If you have a HANDLE that was inherited from your parent process (different from stdin, stdout, or stderr) or a pipe from CreatePipe, is it possible to get a buffered FILE* stream from it? MSDN does document _fdopen, but that works with integer file descriptors returned by _open, not generic HANDLEs.
Unfortunately,
HANDLEs are completely different beasts fromFILE*s and file descriptors. The CRT ultimately handles files in terms ofHANDLEs and associates thoseHANDLEs to a file descriptor. Those file descriptors in turn backs the structure pointer byFILE*.Fortunately, there is a section on this MSDN page that describes functions that “provide a way to change the representation of the file between a FILE structure, a file descriptor, and a Win32 file handle”:
Looks like what you need is
_open_osfhandlefollowed by_fdopento obtain aFILE*from aHANDLE.Here’s an example involving
HANDLEs obtained fromCreateFile(). When I tested it, it shows the first 255 characters of the file “test.txt” and appends ” — Hello World! — ” at the end of the file:This should work for pipes as well.