How do I get the file HANDLE from the fopen FILE structure?

后端 未结 3 1674
面向向阳花
面向向阳花 2020-12-03 09:49

The fopen function returns a pointer to a FILE structure,

相关标签:
3条回答
  • 2020-12-03 10:31

    Use _fileno followed by _get_osfhandle. Don't forget to _close it when you are done.

    EDIT: it's not clear to me that _get_osfhandle is supported on WinCE. However the docs for WinCE _fileno say it returns a "file handle" rather than "descriptor". YMMV but this suggests that you can maybe just use _fileno return 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:

    #ifndef q4_WCE
    
      FlushFileBuffers((HANDLE) _get_osfhandle(_fileno(_file)));
      HANDLE h = ::CreateFileMapping((HANDLE)
    _get_osfhandle(_fileno(_file)),
                            0, PAGE_READONLY, 0, len, 0);
    #else
    
      FlushFileBuffers((HANDLE) _fileno(_file));
      HANDLE h = ::CreateFileMapping((HANDLE) _fileno(_file),
                        0, PAGE_READONLY, 0, len, 0);
    #endif //q4_WCE
    

    It turns out that _fileno returns a handle. You just have to cast it."

    0 讨论(0)
  • 2020-12-03 10:32

    For C, try this

    HANDLE foo = (HANDLE)_get_osfhandle(fileno(fopen("bar.txt", "w")));
    
    0 讨论(0)
  • 2020-12-03 10:39

    On Linux, there's the int fileno(FILE *); function that returns the file descriptor (the one that was returned by the low-level open function) from the FILE*.

    I don't know if it applies to Windows and returns the HANDLE though?

    0 讨论(0)
提交回复
热议问题