Friday, February 18, 2011

_access() doesn't work!?

HELP!

The _access() CRT call does not work on Windows - at least not in the way you'd expect coming from unix or linux. The underscored function found in the Windows C runtime library appears to be a Windows equivalent of the Posix function access() reading the MSDN docs.

But appearances can be deceiving.

The unix and linux variants will throw EACCES when accessing a directory/folder where you have no read access. The windows _access() does not. Help! In fact, _access() only proves usable for checking existence of a given path, and nothing else.

How, then, do you get a proper access() function on Windows? Turns out CreateFile() will do what we need:
DWORD dwAccess = GENERIC_READ; // or GENERIC_WRITE, or both |'d
hFile = CreateFile(fname,
dwAccess,
FILE_SHARE_READ|FILE_SHARE_WRITE, // attempt to open with shared read/write access
NULL, // no security needed for probe
OPEN_EXISTING, // check existing files and folders only
FILE_ATTRIBUTE_NORMAL | FILE_FLAG_BACKUP_SEMANTICS, //both needed for directory probe
NULL); // template file not needed for probe

if (hFile == INVALID_HANDLE_VALUE){
// do whatever you need to handle EACCES
}
CloseHandle(hFile);
...
Hope this can save you a few cycles...