cleanname.c 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. #include "lib9.h"
  2. /*
  3. * In place, rewrite name to compress multiple /, eliminate ., and process ..
  4. */
  5. #define SEP(x) ((x)=='/' || (x) == 0)
  6. char*
  7. cleanname(char *name)
  8. {
  9. char *p, *q, *dotdot;
  10. int rooted, erasedprefix;
  11. rooted = name[0] == '/';
  12. erasedprefix = 0;
  13. /*
  14. * invariants:
  15. * p points at beginning of path element we're considering.
  16. * q points just past the last path element we wrote (no slash).
  17. * dotdot points just past the point where .. cannot backtrack
  18. * any further (no slash).
  19. */
  20. p = q = dotdot = name+rooted;
  21. while(*p) {
  22. if(p[0] == '/') /* null element */
  23. p++;
  24. else if(p[0] == '.' && SEP(p[1])) {
  25. if(p == name)
  26. erasedprefix = 1;
  27. p += 1; /* don't count the separator in case it is nul */
  28. } else if(p[0] == '.' && p[1] == '.' && SEP(p[2])) {
  29. p += 2;
  30. if(q > dotdot) { /* can backtrack */
  31. while(--q > dotdot && *q != '/')
  32. ;
  33. } else if(!rooted) { /* /.. is / but ./../ is .. */
  34. if(q != name)
  35. *q++ = '/';
  36. *q++ = '.';
  37. *q++ = '.';
  38. dotdot = q;
  39. }
  40. if(q == name)
  41. erasedprefix = 1; /* erased entire path via dotdot */
  42. } else { /* real path element */
  43. if(q != name+rooted)
  44. *q++ = '/';
  45. while((*q = *p) != '/' && *q != 0)
  46. p++, q++;
  47. }
  48. }
  49. if(q == name) /* empty string is really ``.'' */
  50. *q++ = '.';
  51. *q = '\0';
  52. if(erasedprefix && name[0] == '#'){
  53. /* this was not a #x device path originally - make it not one now */
  54. memmove(name+2, name, strlen(name)+1);
  55. name[0] = '.';
  56. name[1] = '/';
  57. }
  58. return name;
  59. }