Programming Tips - How do I convert a Window file HANDLE into a stdio FILE * handle?

Date: 2010may6 OS: Windows Language: C/C++ Q. How do I convert a Window file HANDLE into a stdio FILE * handle? A. Use _open_osfhandle() and _fdopen() like this:
#include <stdio.h> #include <io.h> #include <fcntl.h> #if (_MSC_VER >= 1400) // Visual C++ 8.0 (Visual Studio 2005) #define OSF_HANDLE_TYPE intptr_t #else #define OSF_HANDLE_TYPE long #endif FILE *OsHandleToStd(HANDLE h, LPCSTR szMode) { int flags = 0; int n; if (strchr(szMode, 'a')) flags |= O_APPEND; if (strchr(szMode, 'r')) flags |= O_RDONLY; if (strchr(szMode, 't')) flags |= O_TEXT; if ((n = _open_osfhandle((OSF_HANDLE_TYPE)h, flags)) < 0) return NULL; return _fdopen(n, (LPSTR)szMode); } void ExampleUse() // Error checking removed for clarity { HANDLE h; FILE *f; h = OpenForRead("myfile.txt"); // This function is defined elsewhere on davekb.com f = OsHandleToStd(h, "rt"); // Use the above function }