use the -newos toolchain even if -elf is present.
[newos.git] / apps / ls / main.c
blob341543df8e1fb922b4f862603ced3a90d6054f75
1 /*
2 ** Copyright 2002, Travis Geiselbrecht. All rights reserved.
3 ** Distributed under the terms of the NewOS License.
4 */
5 #include <sys/syscalls.h>
6 #include <stdio.h>
7 #include <string.h>
8 #include <stdlib.h>
9 #include <unistd.h>
11 /* globals */
12 void (*disp_func)(const char *, struct file_stat *) = NULL;
13 bool full_list = false;
15 static void display_l(const char *filename, struct file_stat *stat)
17 const char *type;
19 switch(stat->type) {
20 case STREAM_TYPE_FILE:
21 type = "FILE";
22 break;
23 case STREAM_TYPE_DEVICE:
24 type = "DEV ";
25 break;
26 case STREAM_TYPE_DIR:
27 type = "DIR ";
28 break;
29 case STREAM_TYPE_PIPE:
30 type = "PIPE";
31 break;
32 default:
33 type = "UNKN";
36 printf("%s %12Ld %s\n", type, stat->size, filename);
39 // unused
40 static void display(const char *filename, struct file_stat *stat)
42 printf("%s\n", filename);
45 static void usage(const char *progname)
47 printf("usage:\n");
48 printf("%s [-al] [file ...]\n", progname);
50 exit(1);
53 static int do_ls(const char *arg)
55 int rc;
56 int rc2;
57 struct file_stat stat;
58 int count = 0;
60 rc = _kern_rstat(arg, &stat);
61 if(rc < 0) {
62 printf("_kern_rstat() returned error: %s!\n", strerror(rc));
63 return rc;
66 switch(stat.type) {
67 case STREAM_TYPE_DIR: {
68 int fd;
69 char filename[1024];
70 bool done_dot, done_dotdot;
72 fd = _kern_opendir(arg);
73 if(fd < 0) {
74 //printf("ls: opendir() returned error: %s!\n", strerror(fd));
75 break;
78 if(strcmp(arg, ".") != 0) {
79 printf("%s:\n", arg);
82 if(full_list) {
83 done_dot = done_dotdot = false;
84 } else {
85 done_dot = done_dotdot = true;
88 for(;;) {
89 char full_path[1024];
91 if(!done_dot) {
92 strlcpy(filename, ".", sizeof(filename));
93 done_dot = true;
94 } else if(!done_dotdot) {
95 strlcpy(filename, "..", sizeof(filename));
96 done_dotdot = true;
97 } else {
98 rc = _kern_readdir(fd, filename, sizeof(filename));
99 if(rc <= 0)
100 break;
103 full_path[0] = 0;
104 if(strcmp(arg, ".") != 0) {
105 strlcpy(full_path, arg, sizeof(full_path));
106 strlcat(full_path, "/", sizeof(full_path));
108 strlcat(full_path, filename, sizeof(full_path));
110 rc2 = _kern_rstat(full_path, &stat);
111 if(rc2 >= 0) {
112 (*disp_func)(filename, &stat);
114 count++;
116 _kern_closedir(fd);
118 printf("%d files found\n", count);
119 break;
121 default:
122 (*disp_func)(arg, &stat);
123 break;
126 return 0;
129 int main(int argc, char *argv[])
131 char c;
133 disp_func = &display;
135 while((c = getopt(argc, argv, "al")) >= 0) {
136 switch(c) {
137 case 'a':
138 full_list = true;
139 break;
140 case 'l':
141 disp_func = &display_l;
142 break;
143 default:
144 usage(argv[0]);
148 if(optind >= argc) {
149 // no arguments to ls. ls the current dir
150 do_ls(".");
151 } else {
152 for(; optind < argc; optind++) {
153 do_ls(argv[optind]);
157 return 0;