Accessing file-system permission bits
The previous examples,
using RGB colour values,
only employed individual bytes of the integers being considered.
Here we need to access individual bits,
using each bit as if it were a Boolean value (which C11 doesn't directly support).
Recall that we have seen how we can determine if a directory entry
is another directory or a file:
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
.....
struct stat stat_buffer;
if(stat(pathname, &stat_buffer) != 0) {
perror( progname );
}
else if( S_ISDIR( stat_buffer.st_mode )) {
printf( "%s is a directory\n", pathname );
}
else if( S_ISREG( stat_buffer.st_mode )) {
printf( "%s is a file\n", pathname );
}
else {
printf( "%s is unknown!\n", pathname );
}
|
|
// DEFINE A "NEW" TYPE TO REPRESENT A FILE'S MODE
typedef unsigned int mode_t;
struct stat {
....
mode_t st_mode;
....
}
#define S_IFMT 0170000 // BITS DETERMINING FILE TYPE
// File types
#define S_IFDIR 0040000 // DIRECTORY
....
#define S_IFREG 0100000 // REGULAR FILE
// MACROS FOR TESTING FOR DIFFERENT FILE TYPES
#define S_ISDIR(mode) (((mode) & S_IFMT) == (S_IFDIR))
....
#define S_ISREG(mode) (((mode) & S_IFMT) == (S_IFREG))
|
|
This C program better explains demonstrates these concepts:
showmode.c
CITS2002 Systems Programming, Lecture 16, p11, 19th September 2023.
|