The Linux Programming Interface

(nextflipdebug5) #1

296 Chapter 15


Listing 15-3: Header file for file_perms.c
––––––––––––––––––––––––––––––––––––––––––––––––––––––––files/file_perms.h
#ifndef FILE_PERMS_H
#define FILE_PERMS_H

#include <sys/types.h>

#define FP_SPECIAL 1 /* Include set-user-ID, set-group-ID, and sticky
bit information in returned string */

char *filePermStr(mode_t perm, int flags);

#endif
––––––––––––––––––––––––––––––––––––––––––––––––––––––––files/file_perms.h
If the FP_SPECIAL flag is set in the filePermStr() flags argument, then the returned
string includes the settings of the set-user-ID, set-group-ID, and sticky bits, again in
the style of ls(1).
The implementation of the filePermStr() function is shown in Listing 15-4. We
employ this function in the program in Listing 15-1.

Listing 15-4: Convert file permissions mask to string
––––––––––––––––––––––––––––––––––––––––––––––––––––––––files/file_perms.c
#include <sys/stat.h>
#include <stdio.h>
#include "file_perms.h" /* Interface for this implementation */

#define STR_SIZE sizeof("rwxrwxrwx")

char * /* Return ls(1)-style string for file permissions mask */
filePermStr(mode_t perm, int flags)
{
static char str[STR_SIZE];

snprintf(str, STR_SIZE, "%c%c%c%c%c%c%c%c%c",
(perm & S_IRUSR)? 'r' : '-', (perm & S_IWUSR)? 'w' : '-',
(perm & S_IXUSR)?
(((perm & S_ISUID) && (flags & FP_SPECIAL))? 's' : 'x') :
(((perm & S_ISUID) && (flags & FP_SPECIAL))? 'S' : '-'),
(perm & S_IRGRP)? 'r' : '-', (perm & S_IWGRP)? 'w' : '-',
(perm & S_IXGRP)?
(((perm & S_ISGID) && (flags & FP_SPECIAL))? 's' : 'x') :
(((perm & S_ISGID) && (flags & FP_SPECIAL))? 'S' : '-'),
(perm & S_IROTH)? 'r' : '-', (perm & S_IWOTH)? 'w' : '-',
(perm & S_IXOTH)?
(((perm & S_ISVTX) && (flags & FP_SPECIAL))? 't' : 'x') :
(((perm & S_ISVTX) && (flags & FP_SPECIAL))? 'T' : '-'));

return str;
}
––––––––––––––––––––––––––––––––––––––––––––––––––––––––files/file_perms.c
Free download pdf