Last active
September 24, 2019 02:25
-
-
Save amiralles/172134af4462e0c7dc0933994f3eab06 to your computer and use it in GitHub Desktop.
Alternative implementation for the UNIX ls command.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <sys/types.h> | |
#include <sys/stat.h> | |
#include <unistd.h> | |
#include <stdio.h> | |
#include <stdlib.h> | |
#include <dirent.h> | |
#include <pwd.h> | |
#include <grp.h> | |
#include <time.h> | |
void print_permissions(struct stat s); | |
void print_modified(struct stat s); | |
void print_owner(struct stat s); | |
void print_group(struct stat s); | |
int main(int argc, char* argv[]) | |
{ | |
DIR *dir; | |
struct dirent *file; | |
struct stat st; | |
dir = opendir(argv[1]); | |
while ((file = readdir(dir)) != NULL) { | |
stat(file->d_name, &st); | |
print_permissions(st); | |
printf(" %3u", st.st_nlink); | |
print_owner(st); | |
print_group(st); | |
printf(" %10lld", st.st_size); | |
print_modified(st); | |
printf(" %s\n", file->d_name); | |
} | |
closedir(dir); | |
} | |
void print_owner(struct stat s) | |
{ | |
struct passwd *pw = getpwuid(s.st_uid); | |
printf(" %s ", pw->pw_name); | |
} | |
void print_group(struct stat s) | |
{ | |
struct group *gr = getgrgid(s.st_gid); | |
printf(" %s ", gr->gr_name); | |
} | |
void print_permissions(struct stat s) | |
{ | |
printf((S_ISDIR(s.st_mode)) ? "d" : "-"); | |
printf((s.st_mode & S_IRUSR) ? "r" : "-"); | |
printf((s.st_mode & S_IWUSR) ? "w" : "-"); | |
printf((s.st_mode & S_IXUSR) ? "x" : "-"); | |
printf((s.st_mode & S_IRGRP) ? "r" : "-"); | |
printf((s.st_mode & S_IWGRP) ? "w" : "-"); | |
printf((s.st_mode & S_IXGRP) ? "x" : "-"); | |
printf((s.st_mode & S_IROTH) ? "r" : "-"); | |
printf((s.st_mode & S_IWOTH) ? "w" : "-"); | |
printf((s.st_mode & S_IXOTH) ? "x" : "-"); | |
} | |
void print_modified(struct stat s) | |
{ | |
struct tm lt; | |
localtime_r(&s.st_mtime, <); | |
char timbuf[80]; | |
strftime(timbuf, sizeof(timbuf), "%b %d %H:%M", <); | |
printf(" %s", timbuf); | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment