home *** CD-ROM | disk | FTP | other *** search
/ The World of Computer Software / World_Of_Computer_Software-02-385-Vol-1of3.iso / f / find37.zip / find-3.7 / lib / dirname.c < prev    next >
C/C++ Source or Header  |  1992-07-18  |  2KB  |  65 lines

  1. /* dirname.c -- return all but the last element in a path
  2.    Copyright (C) 1990 Free Software Foundation, Inc.
  3.  
  4.    This program is free software; you can redistribute it and/or modify
  5.    it under the terms of the GNU General Public License as published by
  6.    the Free Software Foundation; either version 2, or (at your option)
  7.    any later version.
  8.  
  9.    This program is distributed in the hope that it will be useful,
  10.    but WITHOUT ANY WARRANTY; without even the implied warranty of
  11.    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  12.    GNU General Public License for more details.
  13.  
  14.    You should have received a copy of the GNU General Public License
  15.    along with this program; if not, write to the Free Software
  16.    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.  */
  17.  
  18. #ifdef STDC_HEADERS
  19. #include <stdlib.h>
  20. #else
  21. char *malloc ();
  22. #endif
  23. #if defined(USG) || defined(STDC_HEADERS)
  24. #include <string.h>
  25. #define rindex strrchr
  26. #else
  27. #include <strings.h>
  28. #endif
  29.  
  30. /* Return the leading directories part of PATH,
  31.    allocated with malloc.  If out of memory, return 0.
  32.    Assumes that trailing slashes have already been
  33.    removed.  */
  34.  
  35. char *
  36. dirname (path)
  37.      char *path;
  38. {
  39.   char *newpath;
  40.   char *slash;
  41.   int length;            /* Length of result, not including NUL.  */
  42.  
  43.   slash = rindex (path, '/');
  44.   if (slash == 0)
  45.     {
  46.       /* File is in the current directory.  */
  47.       path = ".";
  48.       length = 1;
  49.     }
  50.   else
  51.     {
  52.       /* Remove any trailing slashes from the result.  */
  53.       while (slash > path && *slash == '/')
  54.     --slash;
  55.  
  56.       length = slash - path + 1;
  57.     }
  58.   newpath = malloc (length + 1);
  59.   if (newpath == 0)
  60.     return 0;
  61.   strncpy (newpath, path, length);
  62.   newpath[length] = 0;
  63.   return newpath;
  64. }
  65.