有没有办法根据C++中WinAPI的CreateFile返回的句柄来创建stdio的FILE*结构?
发布于 2019-01-21 18:23:45
可能是这样的:
#include <Windows.h>
#include <io.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <stddef.h>
// takes ownership of h_file
// caller is responsible for disposing of returned stream descriptor
[[nodiscard]] FILE *
make_stream(HANDLE const h_file)
{
FILE * p_file{};
int const fd{::_open_osfhandle(reinterpret_cast<::intptr_t>(h_file), _O_RDONLY)}; // transferring h_file ownerhip
if(-1 != fd)
{
p_file = ::_fdopen(fd, "r"); // transferring fd ownerhip
if(NULL != p_file)
{
// ok
}
else
{
if(-1 == ::_close(fd))
{
::abort();
}
}
}
else
{
if(FALSE == ::CloseHandle(h_file))
{
::abort();
}
}
return p_file;
}https://stackoverflow.com/questions/54287644
复制相似问题