summary refs log tree commit diff
path: root/progs/ls/ls.c
blob: 976e8c9ac672f980d8a5b62ff773c8648501bb32 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <string.h>
#include <dirent.h>

void joinPath(char *result, const char *base, const char *rel) {
    strcpy(result, base);
    strcat(result, "/");
    strcat(result, rel);
}

int main(int argc, char *argv[]) {
    char dirp[128] = ".";
    if (argc > 1) {
        strcpy(dirp, argv[1]);
    }
    char newpath[128] = {0};
    char newresolvedpath[128] = {0};
    if (dirp[0] == '/') {
        strcpy(newresolvedpath, dirp);
    } else {
        joinPath(newpath, ".", dirp);
        realpath(newpath, newresolvedpath);
    }
    if (!access(newresolvedpath, F_OK)) {
        struct stat statResult;
        stat(newresolvedpath, &statResult);
        if (!S_ISDIR(statResult.st_mode)) {
            write(1, "uuuuh das not a dir\n", 21);
            exit(1);
        }
    } else {
        write(1, "uuuuh das not a dir\n", 21);
        exit(1);
    }
    DIR *d;
    struct dirent *dir;
    d = opendir(dirp);
    //TODO - sort
    if (d) {
        while ((dir = readdir(d)) != NULL) {
            printf("%s\n", dir->d_name);
        }
        closedir(d);
    }
    exit(0);
}