Subversion Repositories Kolibri OS

Rev

Go to most recent revision | Blame | Last modification | View Log | RSS feed

  1. #include <string.h>
  2. #include <stdlib.h>
  3.  
  4. char *dirname (char *path)
  5. {
  6.   static const char dot[] = ".";
  7.   char *last_slash;
  8.   /* Find last '/'.  */
  9.   last_slash = path != NULL ? strrchr (path, '/') : NULL;
  10.   if (last_slash != NULL && last_slash != path && last_slash[1] == '\0')
  11.     {
  12.       /* Determine whether all remaining characters are slashes.  */
  13.       char *runp;
  14.       for (runp = last_slash; runp != path; --runp)
  15.         if (runp[-1] != '/')
  16.           break;
  17.       /* The '/' is the last character, we have to look further.  */
  18.       if (runp != path)
  19.         last_slash = memrchr (path, '/', runp - path);
  20.     }
  21.   if (last_slash != NULL)
  22.     {
  23.       /* Determine whether all remaining characters are slashes.  */
  24.       char *runp;
  25.       for (runp = last_slash; runp != path; --runp)
  26.         if (runp[-1] != '/')
  27.           break;
  28.       /* Terminate the path.  */
  29.       if (runp == path)
  30.         {
  31.           /* The last slash is the first character in the string.  We have to
  32.              return "/".  As a special case we have to return "//" if there
  33.              are exactly two slashes at the beginning of the string.  See
  34.              XBD 4.10 Path Name Resolution for more information.  */
  35.           if (last_slash == path + 1)
  36.             ++last_slash;
  37.           else
  38.             last_slash = path + 1;
  39.         }
  40.       else
  41.         last_slash = runp;
  42.       last_slash[0] = '\0';
  43.     }
  44.   else
  45.     /* This assignment is ill-designed but the XPG specs require to
  46.        return a string containing "." in any case no directory part is
  47.        found and so a static and constant string is required.  */
  48.     path = (char *) dot;
  49.   return path;
  50. }
  51.