| 1 |
/*********************************************************************** |
| 2 |
* Code listing from "Advanced Linux Programming," by CodeSourcery LLC * |
| 3 |
* Copyright (C) 2001 by New Riders Publishing * |
| 4 |
* See COPYRIGHT for license information. * |
| 5 |
***********************************************************************/ |
| 6 |
|
| 7 |
#include <assert.h> |
| 8 |
#include <dirent.h> |
| 9 |
#include <stdio.h> |
| 10 |
#include <string.h> |
| 11 |
#include <sys/stat.h> |
| 12 |
#include <sys/types.h> |
| 13 |
#include <unistd.h> |
| 14 |
|
| 15 |
/* Return a string that describes the type of the file system entry PATH. */ |
| 16 |
|
| 17 |
const char* get_file_type (const char* path) |
| 18 |
{ |
| 19 |
struct stat st; |
| 20 |
lstat (path, &st); |
| 21 |
if (S_ISLNK (st.st_mode)) |
| 22 |
return "symbolic link"; |
| 23 |
else if (S_ISDIR (st.st_mode)) |
| 24 |
return "directory"; |
| 25 |
else if (S_ISCHR (st.st_mode)) |
| 26 |
return "character device"; |
| 27 |
else if (S_ISBLK (st.st_mode)) |
| 28 |
return "block device"; |
| 29 |
else if (S_ISFIFO (st.st_mode)) |
| 30 |
return "fifo"; |
| 31 |
else if (S_ISSOCK (st.st_mode)) |
| 32 |
return "socket"; |
| 33 |
else if (S_ISREG (st.st_mode)) |
| 34 |
return "regular file"; |
| 35 |
else |
| 36 |
/* Unexpected. Each entry should be one of the types above. */ |
| 37 |
assert (0); |
| 38 |
} |
| 39 |
|
| 40 |
int main (int argc, char* argv[]) |
| 41 |
{ |
| 42 |
char* dir_path; |
| 43 |
DIR* dir; |
| 44 |
struct dirent* entry; |
| 45 |
char entry_path[PATH_MAX + 1]; |
| 46 |
size_t path_len; |
| 47 |
|
| 48 |
if (argc >= 2) |
| 49 |
/* If a directory was specified on the command line, use it. */ |
| 50 |
dir_path = argv[1]; |
| 51 |
else |
| 52 |
/* Otherwise, use the current directory. */ |
| 53 |
dir_path = "."; |
| 54 |
/* Copy the directory path into entry_path. */ |
| 55 |
strncpy (entry_path, dir_path, sizeof (entry_path)); |
| 56 |
path_len = strlen (dir_path); |
| 57 |
/* If the directory path doesn't end with a slash, append a slash. */ |
| 58 |
if (entry_path[path_len - 1] != '/') { |
| 59 |
entry_path[path_len] = '/'; |
| 60 |
entry_path[path_len + 1] = '\0'; |
| 61 |
++path_len; |
| 62 |
} |
| 63 |
|
| 64 |
/* Start the listing operation of the directory specified on the |
| 65 |
command line. */ |
| 66 |
dir = opendir (dir_path); |
| 67 |
/* Loop over all directory entries. */ |
| 68 |
while ((entry = readdir (dir)) != NULL) { |
| 69 |
const char* type; |
| 70 |
/* Build the path to the directory entry by appending the entry |
| 71 |
name to the path name. */ |
| 72 |
strncpy (entry_path + path_len, entry->d_name, |
| 73 |
sizeof (entry_path) - path_len); |
| 74 |
/* Determine the type of the entry. */ |
| 75 |
type = get_file_type (entry_path); |
| 76 |
/* Print the type and path of the entry. */ |
| 77 |
printf ("%-18s: %s\n", type, entry_path); |
| 78 |
} |
| 79 |
|
| 80 |
/* All done. */ |
| 81 |
closedir (dir); |
| 82 |
return 0; |
| 83 |
} |