summaryrefslogtreecommitdiff
path: root/ls.c
blob: ec0378262a46d1d88279583ac9ee8443295454df (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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#include <dirent.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>


struct options
{
	unsigned int skip_dots:1;
	unsigned int skip_self_and_up:1;
};


struct options defaults = {
	.skip_dots = 1,
	.skip_self_and_up = 1,
};


int ls(const char * path, struct options opts)
{
	DIR * dir;
	if (NULL == (dir = opendir(path))) {
		perror(path);
		return 1;
	}
	struct dirent * entry;
	while (NULL != (entry = readdir(dir))) {
		const unsigned int is_dot = '.' == entry->d_name[0];
		if (opts.skip_dots && is_dot)
			continue;
		const unsigned int is_self = is_dot && 0 == entry->d_name[1];
		const unsigned int is_up = is_dot && '.' == entry->d_name[1] && 0 == entry->d_name[2];
		if (opts.skip_self_and_up && (is_self || is_up))
			continue;
		printf("%s\n", entry->d_name);
	}
	closedir(dir);
	return 0;
}


int main(int argc, char * argv[])
{
	int opt;
	struct options opts = defaults;
	while (-1 != (opt = getopt(argc, argv, "aA"))) {
		switch (opt) {
		case 'a':
			opts.skip_self_and_up = 0;
			// fall-through
		case 'A':
			opts.skip_dots = 0;
			break;
		default:
			dprintf(2, "Usage: %s [-aA] [file...]\n", argv[0]);
			return 1;
		}
	}
	int res = 0;
	if (optind >= argc)
		res |= ls(".", opts);
	else for (int i = optind; i < argc; ++i)
		res |= ls(argv[i], opts);
	return res;
}