Hi,
I am implementing 'ls' command in c without using 'system' function is there any c function to display the directory permission?
Thanks.
Hi,
I am implementing 'ls' command in c without using 'system' function is there any c function to display the directory permission?
Thanks.
Look into stat()
. Sounds like you're on a Linux or POSIX system, so that should be the way.
Then look at the st_mode
field of the struct stat
, it contains the information about protection bits, which are often collectively called a file's "mode" (as reflected by the chmod
command that changes the settings).
Going from the binary bits to a textual representation like ls' is ... an interesting challenge.
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 on directory entries as well as files and the st_mode
is the specific field you're looking for.
The <sys/stat.h>
header file should contain that structure and all the definitions along with #defines
and/or macros for intelligently decoding the fields (see here for a sample).
If you're interested in how it's really done, you can look at the ls
source code in GNU coreutils. But only use that to educate yourself. It's GPL so you can't just grab it for your own purposes and, if this is homework, your educator will almost certainly fail you if you turn in something that looks too similar to this.