Search code examples
cwindowsmingwfile-descriptor

On Windows/mingw, what is the equivalent of `fcntl(fd, F_GETFL) | O_ACCMODE`?


I am compiling a program on Windows with Mingw. How can I get the access mode for an open file descriptor?


Solution

  • According to Win32.hlp, the API supplies the function BOOL GetFileInformationByHandle(HANDLE hFile, LPBY_HANDLE_FILE_INFORMATION lpFileInformation) in KERNEL32. LPBY_HANDLE_FILE_INFORMATION is a BY_HANDLE_FILE_INFORMATION*, where BY_HANDLE_FILE_INFORMATION is as follows:

    typedef struct _BY_HANDLE_FILE_INFORMATION { // bhfi  
        DWORD    dwFileAttributes; 
        FILETIME ftCreationTime; 
        FILETIME ftLastAccessTime; 
        FILETIME ftLastWriteTime; 
        DWORD    dwVolumeSerialNumber; 
        DWORD    nFileSizeHigh; 
        DWORD    nFileSizeLow; 
        DWORD    nNumberOfLinks; 
        DWORD    nFileIndexHigh; 
        DWORD    nFileIndexLow; 
    } BY_HANDLE_FILE_INFORMATION;
    

    After calling said function, if it returns true, the BY_HANDLE_FILE_INFORMATION contains data pertinent to your file. dwFileAttributes may contain the FILE_ATTRIBUTE_READ_ONLY flag.

    If you want more than that, there is also:

    BOOL GetKernelObjectSecurity(
     HANDLE Handle,                             // handle of object to query
     SECURITY_INFORMATION RequestedInformation, // requested information
     PSECURITY_DESCRIPTOR pSecurityDescriptor,  // address of security descriptor
     DWORD nLength,                             // size of buffer for security descriptor 
     LPDWORD lpnLengthNeeded                    // address of required size of buffer
    );
    

    The API reference is necessarily vague on what a SECURITY_DESCRIPTOR is, but you can call a bunch of other functions using its address as a parameter to get specific properties. The SECURITY_INFORMATION is just a DWORD constant specifying which of these functions you plan to call. You can find more info at http://msdn.microsoft.com/en-us/library/aa446641%28VS.85%29.aspx

    Edit - the second code section keeps coming out looking screwy, but the link to the API reference will lead you where you need to go if you dig around a bit.