1 #include <stdio.h>
2 #include <string.h>
3 #include <sys/stat.h>
4 #include <dirent.h>
5 #include <errno.h>
6
7 bool isRoot(const char* path)
8 {
9 if (strcmp(path, "/") == 0)
10 return true;
11
12 char pp[256] = {0};
13
14 int l = strlen(path);
15 strcpy(pp, path);
16
17 if (pp[l - 1] != '/')
18 {
19 pp[l] = '/';
20 l += 1;
21 }
22
23 strcat(pp, "../");
24
25 struct stat ps;
26 stat(pp, &ps);
27
28 struct stat cs;
29 stat(path, &cs);
30
31 return ps.st_ino == cs.st_ino &&
32 ps.st_nlink == cs.st_nlink &&
33 ps.st_mtime == cs.st_mtime;
34 }
35
36 void printPath(const char* path)
37 {
38 if (isRoot(path))
39 {
40 printf("/");
41 return;
42 }
43
44 char pp[256] = {0};
45
46 int l = strlen(path);
47 strcpy(pp, path);
48
49 if (pp[l - 1] != '/')
50 {
51 pp[l] = '/';
52 l += 1;
53 }
54
55 strcat(pp, "../");
56 printPath(pp);
57
58 DIR* dp = opendir(pp);
59 if (!dp)
60 {
61 printf("Failed to open dir %s\n", pp);
62 return;
63 }
64
65 struct stat s;
66 stat(path, &s);
67
68 char cp[256];
69 while (dirent* en = readdir(dp))
70 {
71 memset(cp, 0, sizeof(cp));
72 strcpy(cp, pp);
73 strcat(cp, en->d_name);
74
75 struct stat cs;
76 stat(cp, &cs);
77
78 if (cs.st_ino == s.st_ino && cs.st_mtime == s.st_mtime)
79 {
80 printf("%s/", en->d_name);
81 break;
82 }
83 }
84 }
85
86 int main(int argc, char* argv[])
87 {
88 printPath("./");
89 printf("\n");
90 return 0;
91 }