How make FILE* from HANDLE in WinApi?

前端 未结 3 2091
别跟我提以往
别跟我提以往 2020-12-01 09:31

Is there easy way to create FILE* from WinApi HANDLE which points to one end of pipe? Something like we do in unix: fdopen(fd,);

3条回答
  •  Happy的楠姐
    2020-12-01 10:14

    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 .

    i didn't test for case 1 and 2, so use it at your own risk.

提交回复
热议问题