首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用CreateFile打开文件*

使用CreateFile打开文件*
EN

Stack Overflow用户
提问于 2019-01-21 18:11:23
回答 1查看 357关注 0票数 3

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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-01-21 18:23:45

可能是这样的:

代码语言:javascript
复制
#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;
}
票数 7
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54287644

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档