Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How make FILE* from HANDLE in WinApi?

Tags:

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,<mode>);

like image 499
Mihran Hovsepyan Avatar asked Mar 04 '11 12:03

Mihran Hovsepyan


People also ask

What is the handle of a file?

A file handle, in the context of computing, is a temporary reference number that an operating system assigns to a file requested by a user to be opened. The system calls, accesses and interacts with the file through that reference number throughout the session until the user terminates the file or the system session.

What is a file handle C++?

File handling in C++ is a mechanism to store the output of a program in a file and help perform various operations on it. Files help store these data permanently on a storage device. The term “Data” is commonly referred to as known facts or information.

Can CreateFile return null?

Since there is a single function to dispose of handles, CloseHandle , it follows that NULL is not a valid HANDLE value. Hence CreateFile cannot ever return NULL .

What is Lpdword?

LPDWORD is just a typedef for DWORD* and when a Windows SDK function parameter is a "LPsomething" you generally need to pass a pointer to a "something" (except for the LP[C][W]STR string types).


2 Answers

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.

like image 68
Greg Hewgill Avatar answered Oct 20 '22 20:10

Greg Hewgill


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.

like image 42
max zhou Avatar answered Oct 20 '22 20:10

max zhou