#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>
#include <pwd.h>
#include <stdlib.h>
#include <grp.h>
#include <time.h>
void ls_al(char *path) {
if (chdir(path) < 0) {
perror("path");
}
DIR *dir = opendir(".");
struct dirent *info;
struct stat buf;
char type = '-', permi[10];
while (info = readdir(dir)) {
if (stat(info->d_name, &buf)) {
perror("stat");
exit(1);
}
switch (buf.st_mode & S_IFMT) {
case S_IFSOCK:
type = 's';
break;
case S_IFLNK:
type = 'l';
break;
case S_IFREG:
type = '-';
break;
case S_IFBLK:
type = 'b';
break;
case S_IFDIR:
type = 'd';
break;
case S_IFCHR:
type = 'c';
break;
case S_IFIFO:
type = 'p';
break;
default:
break;
}
permi[0] = buf.st_mode & S_IRUSR ? 'r' : '-';
permi[1] = buf.st_mode & S_IWUSR ? 'w' : '-';
permi[2] = buf.st_mode & S_IXUSR ? 'x' : '-';
permi[3] = buf.st_mode & S_IRGRP ? 'r' : '-';
permi[4] = buf.st_mode & S_IWGRP ? 'w' : '-';
permi[5] = buf.st_mode & S_IXGRP ? 'x' : '-';
permi[6] = buf.st_mode & S_IROTH ? 'r' : '-';
permi[7] = buf.st_mode & S_IWOTH ? 'w' : '-';
permi[8] = buf.st_mode & S_IXOTH ? 'x' : '-';
struct passwd *pd = getpwuid(buf.st_uid);
struct group *gp = getgrgid(buf.st_gid);
struct tm *mtime = localtime(&buf.st_mtime);
printf("%c%s %3d %s %s %12d %4d/%02d/%02d %02d:%02d:%02d %s\n", type, permi, buf.st_nlink, pd->pw_name,
gp->gr_name, buf.st_size, mtime->tm_year + 1900, mtime->tm_mon + 1, mtime->tm_mday, mtime->tm_hour,
mtime->tm_min, mtime->tm_sec, info->d_name);
}
return ;
}
int main(int argc, char **argv) {
if (argc != 2) {
printf("using: cmd + pathname\n");
return 1;
}
ls_al(argv[1]);
return 0;
}