Lion King
Lion King

Reputation: 33823

How to check whether a directory is readable or writable?

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;

Is there a direct or indirect way to know whether a directory is readable or writable?

Upvotes: 0

Views: 1461

Answers (1)

Rita Han
Rita Han

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.

enter image description here

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

Related Questions