Skip to content

Instantly share code, notes, and snippets.

@devlavender
Created February 3, 2022 14:08
Show Gist options
  • Save devlavender/4c637895486a54a28e026e191104bda3 to your computer and use it in GitHub Desktop.
Save devlavender/4c637895486a54a28e026e191104bda3 to your computer and use it in GitHub Desktop.
ls-like example app using stat (tested on Linux only)
#include <stdio.h>
#include <string.h>
#include <strings.h>
#include <sys/stat.h>
#include <errno.h>
#include <limits.h>
typedef enum {
O_USER_MODE = S_IRWXU,
O_GROUP_MODE = S_IRWXG,
O_OTHERS_MODE = S_IRWXO
} retrieve_type;
typedef enum {
O_READ = S_IRUSR | S_IRGRP | S_IROTH,
O_WRITE = S_IWUSR | S_IWGRP | S_IWOTH,
O_EXEC = S_IXUSR | S_IXGRP | S_IXOTH
} perm_type;
char f_type(const struct stat *const s) {
if (S_ISREG(s->st_mode)) return '-';
if (S_ISDIR(s->st_mode)) return 'd';
if (S_ISCHR(s->st_mode)) return 'c';
if (S_ISBLK(s->st_mode)) return 'b';
if (S_ISFIFO(s->st_mode)) return 'f';
if (S_ISLNK(s->st_mode)) return 'l';
if (S_ISSOCK(s->st_mode)) return 's';
return '?';
}
char f_mode(const struct stat *const s, retrieve_type rtype, perm_type ptype) {
mode_t mode = s->st_mode;
char c = (ptype == O_READ) ? 'r' : ((ptype == O_WRITE) ? 'w' : ((ptype == O_EXEC) ? 'x' : '?'));
if (mode & rtype & ptype) return c;
return '-';
}
int main(int argc, char **argv) {
char *fnames[argc+1];
bzero(fnames, sizeof(fnames));
struct stat stt;
int stt_r = 0;
for (int i = 1; i < argc; i++) {
stt_r = 0;
bzero(&stt, sizeof(struct stat));
//printf("Checking file %s:\n", argv[i]);
stt_r = stat(argv[i], &stt);
if (stt_r == -1) {
char errmsg[301 + PATH_MAX];
snprintf(errmsg, 300+PATH_MAX, "%s: Cannot stat file, errno=%d. Details", argv[1], errno);
errmsg[300+PATH_MAX] = 0;
perror(errmsg);
continue;
}
printf("%c%c%c%c%c%c%c%c%c%c\t%d %d\t%zu\t%s\n",
f_type(&stt),
f_mode(&stt, O_USER_MODE, O_READ),
f_mode(&stt, O_USER_MODE, O_WRITE),
f_mode(&stt, O_USER_MODE, O_EXEC),
f_mode(&stt, O_GROUP_MODE, O_READ),
f_mode(&stt, O_GROUP_MODE, O_WRITE),
f_mode(&stt, O_GROUP_MODE, O_EXEC),
f_mode(&stt, O_OTHERS_MODE, O_READ),
f_mode(&stt, O_OTHERS_MODE, O_WRITE),
f_mode(&stt, O_OTHERS_MODE, O_EXEC),
stt.st_uid, stt.st_gid, stt.st_size, argv[i]
);
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment