getcwd.c 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124
  1. #include <stdlib.h>
  2. #include <errno.h>
  3. #include <sys/stat.h>
  4. #include <dirent.h>
  5. #include <string.h>
  6. /* These functions find the absolute path to the current working directory. */
  7. static char *recurser(); /* Routine to go up tree */
  8. static char *search_dir(); /* Routine to find the step back down */
  9. static char *path_buf;
  10. static int path_size;
  11. static dev_t root_dev;
  12. static ino_t root_ino;
  13. static struct stat st;
  14. char *getcwd( char *buf, int size)
  15. {
  16. path_size = size;
  17. if (size < 3) {
  18. __set_errno(ERANGE);
  19. return NULL;
  20. }
  21. if (buf != NULL)
  22. path_buf = buf;
  23. else
  24. {
  25. path_buf = malloc (size);
  26. if (path_buf == NULL)
  27. return NULL;
  28. }
  29. strcpy(path_buf, ".");
  30. if (stat("/", &st) < 0)
  31. return NULL;
  32. root_dev = st.st_dev;
  33. root_ino = st.st_ino;
  34. return recurser();
  35. }
  36. static char *recurser()
  37. {
  38. dev_t this_dev;
  39. ino_t this_ino;
  40. if (stat(path_buf, &st) < 0)
  41. return 0;
  42. this_dev = st.st_dev;
  43. this_ino = st.st_ino;
  44. if (this_dev == root_dev && this_ino == root_ino) {
  45. strcpy(path_buf, "/");
  46. return path_buf;
  47. }
  48. if (strlen(path_buf) + 4 > path_size) {
  49. __set_errno(ERANGE);
  50. return 0;
  51. }
  52. strcat(path_buf, "/..");
  53. if (recurser() == 0)
  54. return 0;
  55. return search_dir(this_dev, this_ino);
  56. }
  57. static char *search_dir(this_dev, this_ino)
  58. dev_t this_dev;
  59. ino_t this_ino;
  60. {
  61. DIR *dp;
  62. struct dirent *d;
  63. char *ptr;
  64. int slen;
  65. /* The test is for ELKS lib 0.0.9, this should be fixed in the real kernel */
  66. int slow_search = (sizeof(ino_t) != sizeof(d->d_ino));
  67. if (stat(path_buf, &st) < 0)
  68. return 0;
  69. if (this_dev != st.st_dev)
  70. slow_search = 1;
  71. slen = strlen(path_buf);
  72. ptr = path_buf + slen - 1;
  73. if (*ptr != '/') {
  74. if (slen + 2 > path_size) {
  75. __set_errno(ERANGE);
  76. return 0;
  77. }
  78. strcpy(++ptr, "/");
  79. slen++;
  80. }
  81. slen++;
  82. dp = opendir(path_buf);
  83. if (dp == 0)
  84. return 0;
  85. while ((d = readdir(dp)) != 0) {
  86. if (slow_search || this_ino == d->d_ino) {
  87. if (slen + strlen(d->d_name) > path_size) {
  88. __set_errno(ERANGE);
  89. return 0;
  90. }
  91. strcpy(ptr + 1, d->d_name);
  92. if (stat(path_buf, &st) < 0)
  93. continue;
  94. if (st.st_ino == this_ino && st.st_dev == this_dev) {
  95. closedir(dp);
  96. return path_buf;
  97. }
  98. }
  99. }
  100. closedir(dp);
  101. __set_errno(ENOENT);
  102. return 0;
  103. }