1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
|
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>
/** @brief stat file to get modified date and print name */
void print_file(const char* path) {
struct stat *info = malloc(sizeof(struct stat));
stat(path, info);
struct tm mtime;
localtime_r(&(info->st_mtime), &mtime);
free(info);
printf("%04d-%02d-%02d %02d:%02d:%02d %s\n",
mtime.tm_year+1900, mtime.tm_mon+1, mtime.tm_mday,
mtime.tm_hour, mtime.tm_min, mtime.tm_sec,
path);
}
/** @brief list directory tree recursively */
void ls_rec(const char *path) {
DIR *dir = opendir(path); // get directory handle (used until all content is listed)
if (dir == NULL) return; // return early if path is not a directory
struct dirent *entry;
while ((entry = readdir(dir)) != NULL) { // read next file in dir
char full_path[1024]; // current entry name with full path prefix
snprintf(full_path, sizeof(full_path), "%s/%s", path, entry->d_name); // prepend current directory to current entry
if (entry->d_type != DT_DIR) {
print_file(full_path);
continue; // don't try to print files recursively
}
if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0)
continue; // ignore current and parent directory
print_file(full_path);
ls_rec(full_path);
}
closedir(dir); // free directory handle
}
int main(int argc, const char** argv) {
if (argc < 2) {
printf("no input directory!\n");
return 1;
}
ls_rec(argv[1]);
return 0;
}
|