Is there any C function to get permission on directories?

I am trying to implement a command ls

in C without using a function system

.

Is there a C function to get directory / file permissions so I can display them?

Thanks.

0


a source to share


3 answers


The stat () system call takes a filename string and returns the following structure:

struct stat {
    dev_t     st_dev;     /* ID of device containing file */
    ino_t     st_ino;     /* inode number */
    mode_t    st_mode;    /* protection */
    nlink_t   st_nlink;   /* number of hard links */
    uid_t     st_uid;     /* user ID of owner */
    gid_t     st_gid;     /* group ID of owner */
    dev_t     st_rdev;    /* device ID (if special file) */
    off_t     st_size;    /* total size, in bytes */
    blksize_t st_blksize; /* blocksize for filesystem I/O */
    blkcnt_t  st_blocks;  /* number of blocks allocated */
    time_t    st_atime;   /* time of last access */
    time_t    st_mtime;   /* time of last modification */
    time_t    st_ctime;   /* time of last status change */
};

      

This works equally well with directory entries and files, and st_mode

this is the specific field you are looking for.



The header file <sys/stat.h>

should contain this structure and all definitions along with #defines

and / or macros for intelligent decoding of fields (see here for a sample).

If you are wondering how this is done, you can look at the source code ls

at GNU coreutils . But only use this for teaching. It's GPL so you can't just grab it for your own purposes, and if it's homework your educator will almost certainly not help you if you include something like this.

+3


a source


Take a look stat()

. It looks like you are on a Linux or POSIX system, so this should be the case.

Then look in the field st_mode

struct stat

, it contains information about the security bits, which are often collectively referred to as file "mode" (as reflected by the command chmod

that changes the settings).



Moving from binary bits to textual representation such as ls' is ... an interesting challenge.

+2


a source


+2


a source







All Articles