Reputation: 33823
I want a way to know whether a directory/folder is readable or writable. I searched for a direct way to do that by a function or like that but I didn't find it.
I tried to do it indirectly as follow:
Is readable:
WIN32_FIND_DATAA dirData;
HANDLE hDir;
hDir = FindFirstFile("C:\\folder", &dirData);
if (hDir == INVALID_HANDLE_VALUE)
return false;
return true;
Is writable:
DWORD attr = GetFileAttributes(m_dirPath);
if (attr != INVALID_FILE_ATTRIBUTES && attr & FILE_ATTRIBUTE_READONLY)
return false;
return true;
The first code is an indirect way to know whether a directory readable but it is not efficient because when the directory is empty it returns 0 which is not readable.
The second code to check whether a directory is writable but it always returns 1 which is writable although I have changed the directory permission to read-only.
Is there a direct or indirect way to know whether a directory is readable or writable?
Upvotes: 0
Views: 1461
Reputation: 9720
I want a way to know whether a directory/folder is readable or writable.
Directly to try to open the directory with read/write access permission via CreateFile
API:
HANDLE tDir = CreateFile(L"D:\\testNew", GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
if (INVALID_HANDLE_VALUE == tDir)
printf("Open directory failed with error %d \n", GetLastError());
else
printf("Readable. \n");
tDir = CreateFile(L"D:\\testNew", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
if (INVALID_HANDLE_VALUE == tDir)
printf("Open directory failed with error %d \n", GetLastError());
else
printf("Writable. \n");
If it is a read-only directory you will receive access denied error when you open it with GENERIC_WRITE
.
For read-only, the directory maybe set to deny current user to write, however it is not a read-only directory. At this time you will get "This directory is not read-only" result but you still can't write.
Update:
As @RaymondChen pointed out, you can confirm the desired access right to a directory more accurately using file access rights constants. Take FILE_LIST_DIRECTORY
as an example:
tDir = CreateFile(L"D:\\testNew", FILE_LIST_DIRECTORY, 0, NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
if (INVALID_HANDLE_VALUE == tDir)
printf("Open directory failed with error %d \n", GetLastError());
else
printf("Has right to list the contents of the directory.\n");
Upvotes: 1