简体   繁体   English

如何在WinApi中从HANDLE制作FILE *?

[英]How make FILE* from HANDLE in WinApi?

Is there easy way to create FILE* from WinApi HANDLE which points to one end of pipe? 有没有简单的方法从WinApi HANDLE创建指向管道一端的FILE *? Something like we do in unix: fdopen(fd,<mode>); 像我们在unix中做的事: fdopen(fd,<mode>);

You can do this but you have to do it in two steps. 你可以这样做,但你必须分两步完成。 First, call _open_osfhandle() to get a C run-time file descriptor from a Win32 HANDLE value, then call _fdopen() to get a FILE* object from the file descriptor. 首先,调用_open_osfhandle()从Win32 HANDLE值获取C运行时文件描述符,然后调用_fdopen()从文件描述符中获取FILE*对象。

FILE* getReadBinaryFile(LPCWSTR path) {
    HANDLE hFile = CreateFile(path, GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
    if (hFile == INVALID_HANDLE_VALUE) { 
        return nullptr; 
    }
    int nHandle = _open_osfhandle((long)hFile, _O_RDONLY);
    if (nHandle == -1) { 
        ::CloseHandle(hFile);   //case 1
        return nullptr; 
    }
    FILE* fp = _fdopen(nHandle, "rb");
    if (!fp) {
        ::CloseHandle(hFile);  //case 2
    }
    return fp;
}

my code for get an open read binary file descriptor. 我的代码获取一个开放的读取二进制文件描述符

you should use fclose to close FILE* if you don't need it . 如果你不需要,你应该使用fclose关闭FILE *。

i didn't test for case 1 and 2, so use it at your own risk. 我没有测试案例1和案例2,因此使用它需要您自担风险。

你不能交换(转换)他们..如果你需要一个文件与FILE *和HANDLE你需要打开它两次

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM