The fopen function returns a pointer to a FILE structure, which should be considered an opaque value, without dealing with its content or meaning.
On Windows, the C runtime is a wrapper of the Windows API, and the fopen function relies on the CreateFile function. The CreateFile function returns a HANDLE, which is used by other Windows API.
Now, I need to use Windows API deep inside of a library that uses fopen and FILE*. So: is there a way to get the HANDLE from the FILE structure? As this is compiler specific, I mean on the MSVC runtime library.
I understand that this would be an ugly, non-portable hack, and that could broke if Microsoft changes the internal format of FILE… but I’m developing on a closed system (i.e. on a Windows CE embedded system) and refactoring the library would be difficult and time consuming.
Use
_filenofollowed by_get_osfhandle. Don’t forget to_closeit when you are done.EDIT: it’s not clear to me that
_get_osfhandleis supported on WinCE. However the docs for WinCE_filenosay it returns a “file handle” rather than “descriptor”. YMMV but this suggests that you can maybe just use_filenoreturn value directly as a handle on WinCE.EDIT: #2 That theory is supported by this person’s experience.
“If you take a look at the header files that I posted to the list on Jan 29
you can see how I handled the file creation/handle problem. I didn’t have
to replace all FILE* items with HANDLEs. See the following snippet from
fileio.cpp:
It turns out that _fileno returns a handle. You just have to cast it.”