Search code examples
windowsdesktopstat

C stat() function reports that Windows Desktop folder is read-only


Obviously, my desktop is not read-only, however stat() and findfirst() functions report this as non-writable. Should I use some other function instead? Why?

#include <iostream>
#include <ShlObj.h>
#include <sys/stat.h>

int main() {
    PWSTR ppszPath;
    if (::SHGetKnownFolderPath(FOLDERID_Desktop, 0, NULL, &ppszPath)==S_OK) {
        std::wcout << L"Desktop folder: " << ppszPath << L"\n";
        struct _stat64 buf;
        if (_wstat64(ppszPath, &buf)==0) {
            std::wcout << L"Writable: " << ( (buf.st_mode & _S_IWRITE) != 0? "yes": "no") << L"\n";
        }
    }
}

This prints out on Windows7 x64:

Desktop folder: C:\Users\heldepn\Desktop
Writable: no

Solution

  • The "read-only" flag for directories is decorative and does not control whether the directory contents can be modified. Creating files in a directory is controlled by FILE_ADD_FILE, deleting files in a directory is controlled by FILE_DELETE_CHILD, and creating a subdirectory is controlled by FILE_ADD_SUBDIRECTORY.