Initial commit
[cumulus.git] / scandir.cc
1 /* Recursively descend the filesystem and visit each file. */
2
3 #include <stdio.h>
4 #include <stdlib.h>
5 #include <stdint.h>
6 #include <dirent.h>
7 #include <fcntl.h>
8 #include <sys/types.h>
9 #include <sys/stat.h>
10 #include <unistd.h>
11
12 #include <string>
13
14 using std::string;
15
16 void scandir(const string& path);
17
18 void scanfile(const string& path)
19 {
20     struct stat stat_buf;
21     lstat(path.c_str(), &stat_buf);
22
23     printf("%s:\n", path.c_str());
24     printf("  ino=%Ld, perm=%04o, uid=%d, gid=%d, nlink=%d, blksize=%d, size=%Ld\n",
25            (int64_t)stat_buf.st_ino, stat_buf.st_mode & 07777,
26            stat_buf.st_uid, stat_buf.st_gid, stat_buf.st_nlink,
27            (int)stat_buf.st_blksize, (int64_t)stat_buf.st_size);
28
29     switch (stat_buf.st_mode & S_IFMT) {
30     case S_IFIFO:
31     case S_IFSOCK:
32     case S_IFCHR:
33     case S_IFBLK:
34     case S_IFLNK:
35         printf("  special file\n");
36         break;
37     case S_IFREG:
38         printf("  regular file\n");
39         break;
40     case S_IFDIR:
41         printf("  directory\n");
42         scandir(path);
43         break;
44     }
45 }
46
47 void scandir(const string& path)
48 {
49     printf("Scan directory: %s\n", path.c_str());
50
51     DIR *dir = opendir(path.c_str());
52
53     if (dir == NULL) {
54         printf("Error: %m\n");
55         return;
56     }
57
58     struct dirent *ent;
59     while ((ent = readdir(dir)) != NULL) {
60         string filename(ent->d_name);
61         if (filename == "." || filename == "..")
62             continue;
63         printf("  d_name = '%s'\n", filename.c_str());
64         scanfile(path + "/" + filename);
65     }
66
67     closedir(dir);
68 }
69
70 int main(int argc, char *argv[])
71 {
72     scandir(".");
73
74     return 0;
75 }