【问题标题】:Open FILE* using CreateFile使用 CreateFile 打开 FILE*
【发布时间】:2019-06-14 16:56:32
【问题描述】:

有没有办法根据 C++ 中 WinAPI 的 CreateFile 返回的句柄创建 stdio 的 FILE* 结构?

【问题讨论】:

  • 为什么它们无论如何都会相关?
  • @MatthieuBrucher ,我知道至少有 _get_osfhandle(): docs.microsoft.com/en-us/cpp/c-runtime-library/reference/… 。所以反过来是可能的:从现有的FILE* 获取HANDLE
  • @MatthieuBrucher 他们相关。在最低级别,FILE必须包含来自CreateFileHANDLE。 (实际上,这并不完全正确。它可以使用NtCreateFile - 但这不太可能。)
  • 为什么?您想在打开的文件中使用fprintf
  • @i486 ,是的,我想使用像fscanffread这样的stdio函数,获取流缓冲等

标签: c++ file winapi fopen createfile


【解决方案1】:

可能是这样的:

#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;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多