1 /* Recursively descend the filesystem and visit each file. */
19 void scandir(const string& path);
26 if ((stat_buf.st_mode & S_IFMT) != S_IFREG) {
27 printf("file is no longer a regular file!\n");
32 void scanfile(const string& path)
37 lstat(path.c_str(), &stat_buf);
39 printf("%s:\n", path.c_str());
40 printf(" ino=%Ld, perm=%04o, uid=%d, gid=%d, nlink=%d, blksize=%d, size=%Ld\n",
41 (int64_t)stat_buf.st_ino, stat_buf.st_mode & 07777,
42 stat_buf.st_uid, stat_buf.st_gid, stat_buf.st_nlink,
43 (int)stat_buf.st_blksize, (int64_t)stat_buf.st_size);
45 switch (stat_buf.st_mode & S_IFMT) {
51 printf(" special file\n");
54 printf(" regular file\n");
55 /* Be paranoid when opening the file. We have no guarantee that the
56 * file was not replaced between the stat() call above and the open()
57 * call below, so we might not even be opening a regular file. That
58 * the file descriptor refers to a regular file is checked in
59 * dumpfile(). But we also supply flags to open to to guard against
60 * various conditions before we can perform that verification:
61 * - O_NOFOLLOW: in the event the file was replaced by a symlink
62 * - O_NONBLOCK: prevents open() from blocking if the file was
64 * We also add in O_NOATIME, since this may reduce disk writes (for
66 fd = open(path.c_str(), O_RDONLY|O_NOATIME|O_NOFOLLOW|O_NONBLOCK);
68 /* Drop the use of the O_NONBLOCK flag; we only wanted that for file
70 flags = fcntl(fd, F_GETFL);
71 fcntl(fd, F_SETFL, flags & ~O_NONBLOCK);
78 printf(" directory\n");
84 void scandir(const string& path)
86 printf("Scan directory: %s\n", path.c_str());
88 DIR *dir = opendir(path.c_str());
91 printf("Error: %m\n");
96 vector<string> contents;
97 while ((ent = readdir(dir)) != NULL) {
98 string filename(ent->d_name);
99 if (filename == "." || filename == "..")
101 contents.push_back(filename);
104 sort(contents.begin(), contents.end());
106 for (vector<string>::iterator i = contents.begin();
107 i != contents.end(); ++i) {
108 const string& filename = *i;
109 printf(" d_name = '%s'\n", filename.c_str());
110 scanfile(path + "/" + filename);
116 int main(int argc, char *argv[])