SMGreenfield
SMGreenfield

Reputation: 1720

How does one test if a file is LOCKED and/or read-only without opening?

Is there a portable (std::filesystem) method of testing if a file is "locked" or has "read-only" permissions? MacOS Finder, for example, has a "Locked" setting, which is DIFFERENT than the standard POSIX "permissions".

I need to test if a file can be deleted BEFORE I try to do the delete operation. Ideally, I'd like to avoid OPENING the file for R/W as a test.

This is during a SAVE/RENAME process, and (at least in past MacOS filesystems), OS calls to "exchange" two files worked even if the file was "Locked" in the Finder. Because the of the complexity surrounding how files are saved, and how PREVIOUS versions are "preserved", it's just better to know ahead of time so the operation can be avoided.

FURTHER NOTE: Opening a stream as R/W (std::ios::out | std::ios::in) on a LOCKED file with Read & Write permissions will fail with errno = 1 (operation not permitted). If the file is Read only but not locked, it'll fail with errno 13 (permission denied).

A MacOS (Cocoa) specific approach to testing the lock bit is discussed here:

How to check whether a file is locked in Cocoa?

Upvotes: 3

Views: 1465

Answers (1)

SMGreenfield
SMGreenfield

Reputation: 1720

OK -- this may not be the precise answer, but it APPEARS that you can do THIS (as suggested here:

#include <sys/stat.h>

bool IsLocked(std::string& thePath)
{
    bool isLocked = false;

    struct stat buf;
    int retval = stat(thePath.c_str(), &buf);     // NOTE: retval could be an error, like ENOENT (file doesn't exist)
    if (0 != (buf.st_flags & UF_IMMUTABLE)) {
        isLocked = true;
         //is immutable
    }

    return isLocked;
}

In my own code I deal with retval errors in a more robust manner. You should, too!

But NOTE: while this DOES correctly indicate the status of the Finder's Lock bit/flag for the file, it DOES NOT reflect if the file is "read only". The documentation on UF_IMMUTABLE says "file may not be changed" -- which is obviously NOT accurate.

Upvotes: 1

Related Questions