diff options
Diffstat (limited to 'pintos-progos/examples/ls.c')
| -rw-r--r-- | pintos-progos/examples/ls.c | 90 |
1 files changed, 90 insertions, 0 deletions
diff --git a/pintos-progos/examples/ls.c b/pintos-progos/examples/ls.c new file mode 100644 index 0000000..fbe27a1 --- /dev/null +++ b/pintos-progos/examples/ls.c | |||
| @@ -0,0 +1,90 @@ | |||
| 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, size, and inumber of | ||
| 9 | each file is also printed. This won't work until project 4. */ | ||
| 10 | |||
| 11 | #include <syscall.h> | ||
| 12 | #include <stdio.h> | ||
| 13 | #include <string.h> | ||
| 14 | |||
| 15 | static bool | ||
| 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 false; | ||
| 23 | } | ||
| 24 | |||
| 25 | if (isdir (dir_fd)) | ||
| 26 | { | ||
| 27 | char name[READDIR_MAX_LEN]; | ||
| 28 | |||
| 29 | printf ("%s", dir); | ||
| 30 | if (verbose) | ||
| 31 | printf (" (inumber %d)", inumber (dir_fd)); | ||
| 32 | printf (":\n"); | ||
| 33 | |||
| 34 | while (readdir (dir_fd, name)) | ||
| 35 | { | ||
| 36 | printf ("%s", name); | ||
| 37 | if (verbose) | ||
| 38 | { | ||
| 39 | char full_name[128]; | ||
| 40 | int entry_fd; | ||
| 41 | |||
| 42 | snprintf (full_name, sizeof full_name, "%s/%s", dir, name); | ||
| 43 | entry_fd = open (full_name); | ||
| 44 | |||
| 45 | printf (": "); | ||
| 46 | if (entry_fd != -1) | ||
| 47 | { | ||
| 48 | if (isdir (entry_fd)) | ||
| 49 | printf ("directory"); | ||
| 50 | else | ||
| 51 | printf ("%d-byte file", filesize (entry_fd)); | ||
| 52 | printf (", inumber %d", inumber (entry_fd)); | ||
| 53 | } | ||
| 54 | else | ||
| 55 | printf ("open failed"); | ||
| 56 | close (entry_fd); | ||
| 57 | } | ||
| 58 | printf ("\n"); | ||
| 59 | } | ||
| 60 | } | ||
| 61 | else | ||
| 62 | printf ("%s: not a directory\n", dir); | ||
| 63 | close (dir_fd); | ||
| 64 | return true; | ||
| 65 | } | ||
| 66 | |||
| 67 | int | ||
| 68 | main (int argc, char *argv[]) | ||
| 69 | { | ||
| 70 | bool success = true; | ||
| 71 | bool verbose = false; | ||
| 72 | |||
| 73 | if (argc > 1 && !strcmp (argv[1], "-l")) | ||
| 74 | { | ||
| 75 | verbose = true; | ||
| 76 | argv++; | ||
| 77 | argc--; | ||
| 78 | } | ||
| 79 | |||
| 80 | if (argc <= 1) | ||
| 81 | success = list_dir (".", verbose); | ||
| 82 | else | ||
| 83 | { | ||
| 84 | int i; | ||
| 85 | for (i = 1; i < argc; i++) | ||
| 86 | if (!list_dir (argv[i], verbose)) | ||
| 87 | success = false; | ||
| 88 | } | ||
| 89 | return success ? EXIT_SUCCESS : EXIT_FAILURE; | ||
| 90 | } | ||
