You are on page 1of 2

#include<stdio.

h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<unistd.h>
#include<pwd.h>
#include<grp.h>

#ifndef MAJOR
#define MINOR_BITS 8
#define MAJOR(dev) ((unsigned)dev>>MINOR_BITS)
#define MINOR(dev) (dev & 0xF)
#endif
char xtbl[10]="rwxrwxrwx";
static void display_file_type(int st_mode){
switch(st_mode & S_IFMT) // extraxt file type from st_mode
{
case S_IFREG : printf("-"); // regular file
return ;
case S_IFDIR : printf("d"); // directory file
return;
case S_IFCHR : printf("c"); // character file
return;
case S_IFBLK : printf("b"); // block file
return;
case S_IFIFO : printf("p"); // FIFO file
return;
}
}
static void display_access_perm(int st_mode){
char amode[10];
int i,j;
for(i=0,j=(1<<8);i<9;i++,j>>=1)
amode[i] = (st_mode & j) ? xtbl[i]: '-';
if(st_mode & S_ISUID) //check set -UID flag
amode[i] = (amode[2] =='x')?'S' : 's';
if(st_mode & S_ISGID)
amode[i]= (amode[5] =='x')?'G':'g';
if(st_mode & S_ISVTX)
amode[i]=(amode[8] =='x')?'T':'t';
amode[9]='\0';
printf("%s. ",amode);
}
static void long_list(char *path_name){
struct stat st;
struct group *gr;
struct passwd *pw;
if( lstat(path_name,&st)==-1){
perror("lstat");
return;
}
display_file_type(st.st_mode);
display_access_perm(st.st_mode);
printf("%d ",st.st_nlink); //display hard link
gr = getgrgid(st.st_gid); // retrive group name
pw = getpwuid(st.st_uid); // retrive username
printf("%s %S ",pw->pw_name,gr->gr_name);
if((st.st_mode & S_IFMT)==S_IFCHR || (st.st_mode & S_IFMT)==S_IFBLK)
printf("%d, %d ", MAJOR(st.st_rdev),MINOR(st.st_rdev));
else
printf(" %d ", st.st_size);
printf("%s ", ctime(&st.st_mtime));
printf("%s\n",path_name);
}
int main(int argc, char **argv){
if(argc==1){
printf("usage: %s <file_name><...>\n",argv[0]);
exit(1);
}
// do for each file that is passed as cmd line argument
while(--argc>=1){
long_list(*++argv);
}
return 0;
}

You might also like