tags:

views:

232

answers:

3

Hi,

I am implementing 'ls' command in c without using 'system' function is there any c function to display the directory permission?

Thanks.

+2  A: 

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.

unwind
+2  A: 

The stat functions family (stat(), lstat(), fstat()).

Bastien Léonard
+2  A: 

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.

paxdiablo
hi,can you give me one sample 'c' program to do 'ls -l' command?Thanks
yogesh somawar
No, because you haven't even *tried* to do it yourself. I'm here to help people learn, not do their work for them.
paxdiablo