1
0

spwd.c 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <sys/types.h>
  4. #include <sys/stat.h>
  5. #include <dirent.h>
  6. #include <string.h>
  7. #include <unistd.h>
  8. ino_t get_inode(char *);
  9. void printpathto(ino_t);
  10. void inum_to_name(ino_t, char *, int);
  11. int main() {
  12. printpathto(get_inode(".")); /* Print path to current directory */
  13. putchar('\n'); /* Newline after path */
  14. return 0;
  15. }
  16. void printpathto(ino_t this_inode) {
  17. ino_t parent_inode;
  18. char its_name[BUFSIZ];
  19. parent_inode = get_inode("..");
  20. if (this_inode == parent_inode) {
  21. /* Base case: we are at the root directory */
  22. printf("/");
  23. return;
  24. }
  25. chdir(".."); /* Move up one directory */
  26. inum_to_name(this_inode, its_name, BUFSIZ); /* Get directory name */
  27. printpathto(parent_inode); /* Recursive call */
  28. /* Ensure correct formatting: No extra slash */
  29. if (strcmp(its_name, "/") != 0) {
  30. if (parent_inode != this_inode) { /* Avoid leading double slash */
  31. printf("%s%s", (parent_inode == get_inode(".")) ? "" : "/", its_name);
  32. }
  33. }
  34. }
  35. void inum_to_name(ino_t inode_to_find, char *namebuf, int buflen) {
  36. DIR *dir_ptr;
  37. struct dirent *direntp;
  38. dir_ptr = opendir(".");
  39. if (dir_ptr == NULL) {
  40. perror("opendir");
  41. exit(1);
  42. }
  43. while ((direntp = readdir(dir_ptr)) != NULL) {
  44. if (direntp->d_ino == inode_to_find) {
  45. strncpy(namebuf, direntp->d_name, buflen);
  46. namebuf[buflen - 1] = '\0'; /* Ensure null termination */
  47. closedir(dir_ptr);
  48. return;
  49. }
  50. }
  51. fprintf(stderr, "Error: inode %lu not found in directory\n", (unsigned long)inode_to_find);
  52. closedir(dir_ptr);
  53. exit(1);
  54. }
  55. ino_t get_inode(char *fname) {
  56. struct stat info;
  57. if (stat(fname, &info) == -1) {
  58. fprintf(stderr, "Cannot stat ");
  59. perror(fname);
  60. exit(1);
  61. }
  62. return info.st_ino;
  63. }