2 * ls.c - list files and directories
4 * Copyright (c) 2007 Sascha Hauer <s.hauer@pengutronix.de>, Pengutronix
6 * See file CREDITS for list of people who contributed to this
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License version 2
11 * as published by the Free Software Foundation.
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License
19 * along with this program; if not, write to the Free Software
20 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
26 #include <linux/stat.h>
30 #include <stringlist.h>
32 static void ls_one(const char *path
, struct stat
*s
)
35 unsigned long namelen
= strlen(path
);
37 mkmodestr(s
->st_mode
, modestr
);
38 printf("%s %10u %*.*s\n", modestr
, s
->st_size
, namelen
, namelen
, path
);
41 int ls(const char *path
, ulong flags
)
47 struct string_list sl
;
49 string_list_init(&sl
);
54 if (flags
& LS_SHOWARG
&& s
.st_mode
& S_IFDIR
)
55 printf("%s:\n", path
);
57 if (!(s
.st_mode
& S_IFDIR
)) {
66 while ((d
= readdir(dir
))) {
67 sprintf(tmp
, "%s/%s", path
, d
->d_name
);
70 if (flags
& LS_COLUMN
)
71 string_list_add(&sl
, d
->d_name
);
73 ls_one(d
->d_name
, &s
);
78 if (flags
& LS_COLUMN
) {
79 string_list_print_by_column(&sl
);
80 string_list_free(&sl
);
83 if (!(flags
& LS_RECURSIVE
))
92 while ((d
= readdir(dir
))) {
94 if (!strcmp(d
->d_name
, "."))
96 if (!strcmp(d
->d_name
, ".."))
98 sprintf(tmp
, "%s/%s", path
, d
->d_name
);
102 if (s
.st_mode
& S_IFDIR
) {
103 char *norm
= normalise_path(tmp
);
114 static int do_ls(struct command
*cmdtp
, int argc
, char *argv
[])
118 ulong flags
= LS_COLUMN
;
119 struct string_list sl
;
121 while((opt
= getopt(argc
, argv
, "RCl")) > 0) {
124 flags
|= LS_RECURSIVE
| LS_SHOWARG
;
135 if (argc
- optind
> 1)
138 if (optind
== argc
) {
139 ret
= ls(getcwd(), flags
);
143 string_list_init(&sl
);
147 /* first pass: all files */
149 ret
= stat(argv
[o
], &s
);
151 printf("%s: %s: %s\n", argv
[0],
152 argv
[o
], errno_str());
157 if (!(s
.st_mode
& S_IFDIR
)) {
158 if (flags
& LS_COLUMN
)
159 string_list_add(&sl
, argv
[o
]);
167 if (flags
& LS_COLUMN
)
168 string_list_print_by_column(&sl
);
170 string_list_free(&sl
);
174 /* second pass: directories */
176 ret
= stat(argv
[o
], &s
);
182 if (s
.st_mode
& S_IFDIR
) {
183 ret
= ls(argv
[o
], flags
);
197 static const __maybe_unused
char cmd_ls_help
[] =
198 "Usage: ls [OPTION]... [FILE]...\n"
199 "List information about the FILEs (the current directory by default).\n"
200 " -R list subdirectories recursively\n";
202 BAREBOX_CMD_START(ls
)
204 .usage
= "list a file or directory",
205 BAREBOX_CMD_HELP(cmd_ls_help
)