| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677 |
- #include <stdio.h>
- #include <stdlib.h>
- #include <sys/types.h>
- #include <sys/stat.h>
- #include <dirent.h>
- #include <string.h>
- #include <unistd.h>
- ino_t get_inode(char *);
- void printpathto(ino_t);
- void inum_to_name(ino_t, char *, int);
- int main() {
- printpathto(get_inode(".")); /* Print path to current directory */
- putchar('\n'); /* Newline after path */
- return 0;
- }
- void printpathto(ino_t this_inode) {
- ino_t parent_inode;
- char its_name[BUFSIZ];
- parent_inode = get_inode("..");
- if (this_inode == parent_inode) {
- /* Base case: we are at the root directory */
- printf("/");
- return;
- }
- chdir(".."); /* Move up one directory */
- inum_to_name(this_inode, its_name, BUFSIZ); /* Get directory name */
- printpathto(parent_inode); /* Recursive call */
- /* Ensure correct formatting: No extra slash */
- if (strcmp(its_name, "/") != 0) {
- if (parent_inode != this_inode) { /* Avoid leading double slash */
- printf("%s%s", (parent_inode == get_inode(".")) ? "" : "/", its_name);
- }
- }
- }
- void inum_to_name(ino_t inode_to_find, char *namebuf, int buflen) {
- DIR *dir_ptr;
- struct dirent *direntp;
- dir_ptr = opendir(".");
- if (dir_ptr == NULL) {
- perror("opendir");
- exit(1);
- }
- while ((direntp = readdir(dir_ptr)) != NULL) {
- if (direntp->d_ino == inode_to_find) {
- strncpy(namebuf, direntp->d_name, buflen);
- namebuf[buflen - 1] = '\0'; /* Ensure null termination */
- closedir(dir_ptr);
- return;
- }
- }
- fprintf(stderr, "Error: inode %lu not found in directory\n", (unsigned long)inode_to_find);
- closedir(dir_ptr);
- exit(1);
- }
- ino_t get_inode(char *fname) {
- struct stat info;
- if (stat(fname, &info) == -1) {
- fprintf(stderr, "Cannot stat ");
- perror(fname);
- exit(1);
- }
- return info.st_ino;
- }
|