5907a6cedb90ab507e6f4feee4502f385c1bcdd7
[pintos-anon] / src / examples / ls.c
1 /* ls.c
2   
3    Lists the contents of the directory or directories named on
4    the command line, or of the current directory if none are
5    named.
6
7    By default, only the name of each file is printed.  If "-l" is
8    given as the first argument, the type and size of each file is
9    also printed. */
10
11 #include <syscall.h>
12 #include <stdio.h>
13 #include <string.h>
14
15 static void
16 list_dir (const char *dir, bool verbose) 
17 {
18   int dir_fd = open (dir);
19   if (dir_fd == -1) 
20     {
21       printf ("%s: not found\n", dir);
22       return; 
23     }
24
25   if (isdir (dir_fd))
26     {
27       char name[READDIR_MAX_LEN];
28       printf ("%s:\n", dir);
29       while (readdir (dir_fd, name)) 
30         {
31           printf ("%s", name); 
32           if (verbose) 
33             {
34               char full_name[128];
35               int entry_fd;
36
37               if (strcmp (dir, "."))
38                 snprintf (full_name, sizeof full_name, "%s/%s", dir, name);
39               else 
40                 {
41                   /* This is a special case for implementations
42                      that don't fully understand . and .. */
43                   strlcpy (full_name, name, sizeof full_name); 
44                 }
45               entry_fd = open (full_name);
46
47               printf (": ");
48               if (entry_fd != -1)
49                 {
50                   if (isdir (entry_fd))
51                     printf ("directory");
52                   else
53                     printf ("%d-byte file", filesize (entry_fd));
54                 }
55               else
56                 printf ("open failed");
57               close (entry_fd);
58             }
59           printf ("\n");
60         }
61     }
62   else 
63     printf ("%s: not a directory\n", dir);
64   close (dir_fd); 
65 }
66
67 int
68 main (int argc, char *argv[]) 
69 {
70   bool verbose = false;
71   if (argc > 1 && !strcmp (argv[1], "-l")) 
72     {
73       verbose = true;
74       argv++;
75       argc--;
76     }
77   
78   if (argc <= 1)
79     list_dir (".", verbose);
80   else 
81     {
82       int i;
83       for (i = 1; i < argc; i++)
84         list_dir (argv[i], verbose);
85     }
86   return 0;
87 }