我如何从FOPEN文件结构的文件句柄? [英] How do I get the file HANDLE from the fopen FILE structure?

查看:448
本文介绍了我如何从FOPEN文件结构的文件句柄?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

的fopen 函数返回指向一个文件结构,这应该被视为一个不透明的价值,而不应对其内容或含义。

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.

现在,我需要使用Windows API的内心深处,它使用的库的fopen 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.

据我了解,这将是一个丑陋的,非便携式黑客,如果微软修改文件 ...但我开发的内部格式可能爆发一个封闭的系统(即一个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 文档说它返回一个文件句柄,而不是描述。因人而异,但是这表明你也许可以只使用 _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这个理论是由支持这个人的经历

#2 That theory is supported by this person's experience.

如果你看看我贴到列表01月29头文件
你可以看到我是如何处理的文件创建/处理问题。我没有
以取代处理所有FILE *项目。看到下面的代码片段
fileio.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文件结构的文件句柄?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆