Max0u
Max0u

Reputation: 720

stat st_mode is always equal to 16877

I want to know if a file is a directory or a regular file with stat :

#define _DEFAULT_SOURCE

#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>

int is_regular_file(const char *path)
{
    struct stat path_stat;
    stat(path, &path_stat);
    return S_ISREG(path_stat.st_mode);
}

I try on Mac and Linux and when I print S_ISREG(path_stat.st_mode) is always equal to 1 and path_stat.st_mode is always equal to 16877.

Upvotes: 4

Views: 6207

Answers (2)

Thomas Dickey
Thomas Dickey

Reputation: 54465

16877 is octal 40755, which denotes a directory (octal 40000) with permissions 755 (user has full rights, everyone else has read and traversal rights). As suggested, the stat and chmod manual pages are useful.

Just for example, here is a screenshot with my directory-editor showing octal modes (an option) rather than the usual symbol ones:

ded showing octal permissions

Upvotes: 9

Martin Rosenau
Martin Rosenau

Reputation: 18493

path_stat.st_mode is always equal to 16877

The value of st_mode has to be interpreted by bits:

The low 12 bits are the file access permissions that you can set with chmod. Each bit represents one file permission. The high 4 bits are the file type.

The low 12 bits of the 16-bit number 16877 would be 000111101101. This combination means:

---rwxr-xr-x (read, write, execute for the owner of the file; read and execute for others). This combination is typical for directories and for executable files.

The high 4 bits of the number 16877 are 4 which (at least on Linux mean): "Directory".

S_ISREG(path_stat.st_mode) is always equal to ...

The S_ISREG macro simply checks if the upper 4 bits of the argument have the value that means: "File type is a regular file."

... is always equal to 1

This confuses me a little: 16877 should be a directory; however S_ISREG should return 1 for regular files and 0 for anything else (such as directories).

Upvotes: 3

Related Questions