#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <dirent.h>
#include <unistd.h>
#include <limits.h>
#include <pwd.h>
#include <grp.h>
#include <sys/stat.h>
#include <sys/sysmacros.h>
#include <sys/xattr.h>
struct entry {
char name[NAME_MAX + 1];
struct stat st;
char target[PATH_MAX];
int is_link;
int has_acl;
};
static int cmp(const void *a, const void *b) {
const struct entry *x = a, *y = b;
return strcmp(x->name, y->name);
}
static void mode_string(mode_t m, char *s) {
if (S_ISREG(m)) s[0] = '-';
else if (S_ISDIR(m)) s[0] = 'd';
else if (S_ISLNK(m)) s[0] = 'l';
else if (S_ISCHR(m)) s[0] = 'c';
else if (S_ISBLK(m)) s[0] = 'b';
else if (S_ISFIFO(m)) s[0] = 'p';
else if (S_ISSOCK(m)) s[0] = 's';
else s[0] = '?';
const char *rwx = "rwxrwxrwx";
for (int i = 0; i < 9; i++)
s[i + 1] = (m & (1 << (8 - i))) ? rwx[i] : '-';
if (m & S_ISUID) s[3] = (m & S_IXUSR) ? 's' : 'S';
if (m & S_ISGID) s[6] = (m & S_IXGRP) ? 's' : 'S';
if (m & S_ISVTX) s[9] = (m & S_IXOTH) ? 't' : 'T';
s[10] = '\0';
}
static int num_width(unsigned long v) {
int w = 1;
while (v >= 10) { v /= 10; w++; }
return w;
}
int main(int argc, char *argv[]) {
const char *dir = argc > 1 ? argv[1] : ".";
DIR *d = opendir(dir);
if (!d) {
perror(dir);
return 1;
}
struct entry *e = NULL;
int n = 0, cap = 0;
struct dirent *de;
while ((de = readdir(d)) != NULL) {
if (n == cap) {
cap = cap ? cap * 2 : 64;
e = realloc(e, cap * sizeof(*e));
if (!e) {
perror("realloc");
return 1;
}
}
struct entry *x = &e[n];
strcpy(x->name, de->d_name);
char path[PATH_MAX];
snprintf(path, sizeof(path), "%s/%s", dir, de->d_name);
if (lstat(path, &x->st) == -1) {
perror(path);
continue;
}
x->is_link = S_ISLNK(x->st.st_mode);
// как в ls Ubuntu: "+" после прав, если у файла есть расширенные атрибуты
// (ACL, capabilities); у символьной ссылки смотрится файл, на который она указывает
char names[1024];
ssize_t nx = listxattr(path, names, sizeof(names));
x->has_acl = nx > 0 || (nx == -1 && errno == ERANGE);
if (x->is_link) {
ssize_t len = readlink(path, x->target, sizeof(x->target) - 1);
x->target[len > 0 ? len : 0] = '\0';
}
n++;
}
closedir(d);
qsort(e, n, sizeof(*e), cmp);
// Первый проход: ширины колонок и "total" (в блоках по 1 КиБ)
long long total = 0;
int any_acl = 0;
int w_link = 1, w_user = 0, w_group = 0, w_size = 1, w_major = 0, w_minor = 0, w_dev = 0;
for (int i = 0; i < n; i++) {
struct stat *st = &e[i].st;
total += st->st_blocks;
if (e[i].has_acl) any_acl = 1;
if (num_width(st->st_nlink) > w_link) w_link = num_width(st->st_nlink);
struct passwd *pw = getpwuid(st->st_uid);
int lu = pw ? (int)strlen(pw->pw_name) : num_width(st->st_uid);
struct group *gr = getgrgid(st->st_gid);
int lg = gr ? (int)strlen(gr->gr_name) : num_width(st->st_gid);
if (lu > w_user) w_user = lu;
if (lg > w_group) w_group = lg;
if (S_ISCHR(st->st_mode) || S_ISBLK(st->st_mode)) {
int wa = num_width(major(st->st_rdev));
int wb = num_width(minor(st->st_rdev));
if (wa > w_major) w_major = wa;
if (wb > w_minor) w_minor = wb;
if (wa + 2 + wb > w_dev) w_dev = wa + 2 + wb;
} else if (num_width(st->st_size) > w_size) {
w_size = num_width(st->st_size);
}
}
// ширина колонки размера: самое длинное число или самая длинная пара "major, minor"
if (w_dev > w_size)
w_size = w_dev;
printf("total %lld\n", total / 2);
time_t now = time(NULL);
for (int i = 0; i < n; i++) {
struct stat *st = &e[i].st;
char mode[11];
mode_string(st->st_mode, mode);
struct passwd *pw = getpwuid(st->st_uid);
struct group *gr = getgrgid(st->st_gid);
char user[32], group[32];
if (pw) snprintf(user, sizeof(user), "%s", pw->pw_name);
else snprintf(user, sizeof(user), "%u", st->st_uid);
if (gr) snprintf(group, sizeof(group), "%s", gr->gr_name);
else snprintf(group, sizeof(group), "%u", st->st_gid);
char tbuf[32];
struct tm tm;
localtime_r(&st->st_mtime, &tm);
// как в ls: файлы старше полугода показываются с годом вместо времени
if (st->st_mtime > now || now - st->st_mtime > 15778476)
strftime(tbuf, sizeof(tbuf), "%b %e %Y", &tm);
else
strftime(tbuf, sizeof(tbuf), "%b %e %H:%M", &tm);
// если хотя бы у одного файла есть ACL, ls добавляет колонку под "+" у всех строк
const char *acl = any_acl ? (e[i].has_acl ? "+" : " ") : "";
printf("%s%s %*lu %-*s %-*s ", mode, acl, w_link, (unsigned long)st->st_nlink,
w_user, user, w_group, group);
if (S_ISCHR(st->st_mode) || S_ISBLK(st->st_mode))
printf("%*u, %*u", w_size - w_minor - 2 > w_major ? w_size - w_minor - 2 : w_major,
major(st->st_rdev),
w_minor, minor(st->st_rdev));
else
printf("%*lld", w_size, (long long)st->st_size);
printf(" %s %s", tbuf, e[i].name);
if (e[i].is_link)
printf(" -> %s", e[i].target);
printf("\n");
}
free(e);
return 0;
}