Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Open FILE* using CreateFile

Is there a way to create stdio's FILE* structure on the basis of a handle returned by WinAPI's CreateFile in C++?

like image 477
Serge Rogatch Avatar asked Sep 13 '26 07:09

Serge Rogatch


1 Answers

Maybe like this:

#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;
}
like image 100
user7860670 Avatar answered Sep 15 '26 00:09

user7860670



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!