如何从 fopen FILE 结构中获取文件句柄?
fopen
函数返回一个指向FILE
结构,应将其视为不透明值,而不处理其内容或含义。
在 Windows 上,C 运行时是 Windows API 的包装器,fopen
函数依赖于 CreateFile
函数。 CreateFile
函数返回一个HANDLE
,供其他 Windows API 使用。
现在,我需要在使用 fopen
和 FILE*
的库内部深入使用 Windows API。那么:有没有办法从 FILE
结构中获取 HANDLE
?由于这是特定于编译器的,我指的是 MSVC 运行时库。
我知道这将是一个丑陋的、不可移植的黑客行为,如果微软改变FILE
的内部格式,这可能会破坏......但我正在一个封闭的系统上开发(即在Windows上) CE嵌入式系统)和重构库将是困难且耗时的。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用
_fileno
后跟_get_osfhandle
。完成后不要忘记_close
它。编辑:我不清楚 WinCE 是否支持
_get_osfhandle
。然而,WinCE_fileno
的文档说它返回“文件句柄”而不是“描述符”。 YMMV 但这表明您可以直接使用_fileno
返回值作为 WinCE 上的句柄。编辑:#2该理论得到此人的经验。
“如果你看一下我 1 月 29 日发布到列表中的头文件
您可以看到我如何处理文件创建/处理问题。我没有
用句柄替换所有 FILE* 项。请参阅以下片段
fileio.cpp:
事实证明_fileno返回一个句柄。你只需要施展它就可以了。”
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:
It turns out that _fileno returns a handle. You just have to cast it."
在 Linux 上,有一个
int fileno(FILE *);
函数从返回文件描述符(由低级
open
函数返回的文件描述符) >文件*。我不知道它是否适用于 Windows 并返回句柄?
On Linux, there's the
int fileno(FILE *);
function that returns the file descriptor (the one that was returned by the low-levelopen
function) from theFILE*
.I don't know if it applies to Windows and returns the HANDLE though?
对于C,试试这个
For C, try this