Back to index

nagios-plugins  1.4.16
basename.c
Go to the documentation of this file.
00001 /* basename.c -- return the last element in a file name
00002 
00003    Copyright (C) 1990, 1998-2001, 2003-2006, 2009-2010 Free Software
00004    Foundation, Inc.
00005 
00006    This program is free software: you can redistribute it and/or modify
00007    it under the terms of the GNU General Public License as published by
00008    the Free Software Foundation; either version 3 of the License, or
00009    (at your option) any later version.
00010 
00011    This program is distributed in the hope that it will be useful,
00012    but WITHOUT ANY WARRANTY; without even the implied warranty of
00013    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
00014    GNU General Public License for more details.
00015 
00016    You should have received a copy of the GNU General Public License
00017    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
00018 
00019 #include <config.h>
00020 
00021 #include "dirname.h"
00022 
00023 #include <string.h>
00024 #include "xalloc.h"
00025 #include "xstrndup.h"
00026 
00027 char *
00028 base_name (char const *name)
00029 {
00030   char const *base = last_component (name);
00031   size_t length;
00032 
00033   /* If there is no last component, then name is a file system root or the
00034      empty string.  */
00035   if (! *base)
00036     return xstrndup (name, base_len (name));
00037 
00038   /* Collapse a sequence of trailing slashes into one.  */
00039   length = base_len (base);
00040   if (ISSLASH (base[length]))
00041     length++;
00042 
00043   /* On systems with drive letters, `a/b:c' must return `./b:c' rather
00044      than `b:c' to avoid confusion with a drive letter.  On systems
00045      with pure POSIX semantics, this is not an issue.  */
00046   if (FILE_SYSTEM_PREFIX_LEN (base))
00047     {
00048       char *p = xmalloc (length + 3);
00049       p[0] = '.';
00050       p[1] = '/';
00051       memcpy (p + 2, base, length);
00052       p[length + 2] = '\0';
00053       return p;
00054     }
00055 
00056   /* Finally, copy the basename.  */
00057   return xstrndup (base, length);
00058 }