1

I am trying to optimize a legacy application written in C which makes uses of regular stdio.h resp. fcntl.h functions. For special uses, I would like to inject a few extra hints from https://learn.microsoft.com/en-us/windows/win32/fileio/file-attribute-constants to newly opened file handles.

But those are available only to low-level Win32 APIs. Is there a way to pass the FILE_ATTRIBUTE_... options to the open() call somehow? Or is there somewhere a sane wrapper which would open a file handle "win32 way" with custom options and hand it over as integer file descriptor just like open() would do it?

Simon Mourier
  • 132,049
  • 21
  • 248
  • 298
  • 1
    It's not clear if you need to _open_ the file with those attributes or you can set them after the fact. Seems there may be an API call you can make to get the `HANDLE` to the file descriptor using `_get_osfhanle(fileno(fp))` where `fp` is your `FILE*`. Something you can try, at least. – Chad Dec 14 '22 at 14:13
  • 1
    There is no way to make `open` act like `CreateFile`. `open` has requirements set by POSIX that don't align to Win32. Furthermore it's not even part of the C standard but a method that MSVC supports out of convenience. C would have you use `FILE*`. If you must do what you're asking you can use [`_open_osfhandle`](https://learn.microsoft.com/en-us/cpp/c-runtime-library/reference/open-osfhandle?source=recommendations&view=msvc-170) after using `CreateFile`. But be aware you still need to close the OS handle with `CloseHandle` and manage all the cleanup quirks. – Mgetz Dec 14 '22 at 14:20
  • 1
    https://stackoverflow.com/questions/7359188/how-do-i-retrieve-the-file-of-a-createfile-result – Hans Passant Dec 14 '22 at 16:31

1 Answers1

0

There are two functions that convert between Win32 file handles and file descriptors:

Note that for both:

The _open_osfhandle call transfers ownership of the Win32 file handle to the file descriptor. To close a file opened by using _open_osfhandle, call _close

To close a file whose operating system (OS) file handle is obtained by _get_osfhandle, call _close on the file descriptor fd. Never call CloseHandle on the return value of this function. ...

If you want to set the attributes at creation time, you would need to use CreateFile and then convert to a fd, because afaics there is no API to set attributes on a given HANDLE, there's only SetFileAttributes which operates on a name.

If you just wanna query the attributes, you can use GetFileInformationByHandle.

Martin Ba
  • 37,187
  • 33
  • 183
  • 337