如何从 fopen FILE 结构中获取文件 HANDLE? [英] How do I get the file HANDLE from the fopen FILE structure?
问题描述
fopen
函数返回一个指向 FILE
结构的指针,应该将其视为不透明值,而不处理其内容或含义.
The fopen
function returns a pointer to a FILE
structure, which should be considered an opaque value, without dealing with its content or meaning.
在 Windows 上,C 运行时是 Windows API 的包装器,fopen
函数依赖于 CreateFile
函数.CreateFile
函数返回一个 HANDLE
,供其他 Windows API 使用.
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.
现在,我需要在使用 fopen
和 FILE*
的库的深处使用 Windows API.那么:有没有办法从 FILE
结构中获取 HANDLE
?由于这是特定于编译器的,我的意思是在 MSVC 运行时库上.
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.
我知道这将是一个丑陋的、不可移植的 hack,如果 Microsoft 更改 FILE
的内部格式,这可能会破坏......但我正在一个封闭的系统上开发(即在 Windows CE 嵌入式系统上)并且重构库将是困难和耗时的.
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.
推荐答案
使用 _fileno
后跟 _get_osfhandle
.完成后不要忘记_close
它.
Use _fileno
followed by _get_osfhandle
. Don't forget to _close
it when you are done.
我不清楚 _get_osfhandle
在 WinCE 上是否受支持.然而,WinCE _fileno
的文档说它返回一个文件句柄"而不是描述符".YMMV 但这表明您可以直接使用 _fileno
返回值作为 WinCE 上的句柄.
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.
#2 此人的经验支持该理论.
如果你看看我在 1 月 29 日发布到列表中的头文件你可以看到我是如何处理文件创建/处理问题的.我没有用句柄替换所有 FILE* 项目.请参阅以下片段文件io.cpp:
"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
事实证明 _fileno 返回一个句柄.你只需要投射它."
It turns out that _fileno returns a handle. You just have to cast it."
这篇关于如何从 fopen FILE 结构中获取文件 HANDLE?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!