-
-
Save arlandism/7d29f545d13f2809141422df40d2e23c to your computer and use it in GitHub Desktop.
This file contains 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 <stdio.h> | |
#include <stdlib.h> | |
#include <dirent.h> | |
#include <sys/stat.h> | |
#include <string.h> | |
#define GRN "\e[0;32m" | |
#define BLU "\e[0;34m" | |
#define reset "\e[0m" | |
#define DEFAULT_DIR "./" | |
int print_file(const char* dirname, const char* filename){ | |
int dirlen = strlen(dirname); | |
int pathlen = strlen(filename); | |
char path[dirlen + pathlen + 1]; | |
int cx = snprintf(path, dirlen + pathlen + 2, "%s/%s", dirname, filename); | |
if (cx < 0 || cx >= dirlen + pathlen + 2) { | |
printf("%d\n", cx); | |
printf("Error getting pathname\n"); | |
return -1; | |
} | |
struct stat * fstat = malloc(sizeof(stat)); | |
if (stat(path, fstat) != 0) { //TODO: surely there is a better way to do this than make a syscall per file (e.g. batching of some sort?) | |
printf("Error reading: %s\n", path); | |
free(fstat); | |
return -1; | |
} | |
printf(BLU "%8lld %ld %s\n" reset, fstat->st_size, fstat->st_atimespec.tv_nsec, filename); | |
free(fstat); | |
return 1; | |
} | |
int print_dir(char* dirname){ | |
printf(GRN "%s " reset "contents:\n", dirname); | |
DIR *d = opendir(dirname); | |
if (d == NULL) | |
{ | |
return (1); | |
} | |
struct dirent *entry; | |
while ((entry = readdir(d)) != NULL) | |
{ | |
print_file(dirname, entry->d_name); | |
} | |
printf("\n"); | |
(void) closedir(d); | |
return 0; | |
} | |
int main(int argc, char* argv[argc + 1]) | |
{ | |
if (argc > 1) { | |
for (int i = 1; i < argc; i++) { | |
char *dirname = argv[i]; | |
if (print_dir(dirname) != 0) | |
{ | |
printf("Error printing dir: %s\n", dirname); | |
}; | |
} | |
} else { | |
print_dir(DEFAULT_DIR); | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example output:
╰─$ ./ls ./ contents: 352 138685653 . 768 509013089 .. 1559 77268256 ls.c 24 192662306 Makefile 763 665848454 foo.c 120 873638825 README.md 49424 115866863 a.out 128 584228239 foo 279 806841821 bar.c 50136 909695409 ls 384 348867757 .git