c - Is there a Windows equivalent to fdopen for HANDLEs? -


in unix, if have file descriptor (e.g. socket, pipe, or inherited parent process), can open buffered i/o file* stream on fdopen(3).

is there equivalent on windows handles? if have handle inherited parent process (different stdin, stdout, or stderr) or pipe createpipe, possible buffered file* stream it? msdn document _fdopen, works integer file descriptors returned _open, not generic handles.

unfortunately, handles different beasts file*s , file descriptors. crt handles files in terms of handles , associates handles file descriptor. file descriptors in turn backs structure pointer file*.

fortunately, there section on this msdn page describes functions "provide way change representation of file between file structure, file descriptor, , win32 file handle":

  • _fdopen, _wfdopen: associates stream file opened low-level i/o , returns pointer open stream.
  • _fileno: gets file descriptor associated stream.
  • _get_osfhandle: return operating-system file handle associated existing c run-time file descriptor
  • _open_osfhandle: associates c run-time file descriptor existing operating-system file handle.

looks need _open_osfhandle followed _fdopen obtain file* handle.

here's example involving handles obtained createfile(). when tested it, shows first 255 characters of file "test.txt" , appends " --- hello world! --- " @ end of file:

#include <windows.h> #include <io.h> #include <fcntl.h> #include <cstdio>  int main() {     handle h = createfile("test.txt", generic_read | generic_write, 0, 0,         open_always, file_attribute_normal, 0);     if(h != invalid_handle_value)     {         int fd = _open_osfhandle((intptr_t)h, _o_append | _o_rdonly);         if(fd != -1)         {             file* f = _fdopen(fd, "a+");             if(f != 0)             {                 char rbuffer[256];                 memset(rbuffer, 0, 256);                 fread(rbuffer, 1, 255, f);                 printf("read: %s\n", rbuffer);                 fseek(f, 0, seek_cur); // switch read write                 const char* wbuffer = " --- hello world! --- \n";                 fwrite(wbuffer, 1, strlen(wbuffer), f);                 fclose(f); // calls _close()             }             else             {                 _close(fd); // calls closehandle()             }         }         else         {             closehandle(h);         }     } } 

this should work pipes well.


Comments

Popular posts from this blog

asp.net mvc - SSO between MVCForum and Umbraco7 -

Python Tkinter keyboard using bind -

ubuntu - Selenium Node Not Connecting to Hub, Not Opening Port -