Blame lib/basename.c

Packit 33f14e
/* basename.c -- return the last element in a file name
Packit 33f14e
Packit 33f14e
   Copyright (C) 1990, 1998-2001, 2003-2006, 2009-2017 Free Software
Packit 33f14e
   Foundation, Inc.
Packit 33f14e
Packit 33f14e
   This program is free software: you can redistribute it and/or modify
Packit 33f14e
   it under the terms of the GNU General Public License as published by
Packit 33f14e
   the Free Software Foundation; either version 3 of the License, or
Packit 33f14e
   (at your option) any later version.
Packit 33f14e
Packit 33f14e
   This program is distributed in the hope that it will be useful,
Packit 33f14e
   but WITHOUT ANY WARRANTY; without even the implied warranty of
Packit 33f14e
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
Packit 33f14e
   GNU General Public License for more details.
Packit 33f14e
Packit 33f14e
   You should have received a copy of the GNU General Public License
Packit 33f14e
   along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
Packit 33f14e
Packit 33f14e
#include <config.h>
Packit 33f14e
Packit 33f14e
#include "dirname.h"
Packit 33f14e
Packit 33f14e
#include <string.h>
Packit 33f14e
#include "xalloc.h"
Packit 33f14e
#include "xstrndup.h"
Packit 33f14e
Packit 33f14e
char *
Packit 33f14e
base_name (char const *name)
Packit 33f14e
{
Packit 33f14e
  char const *base = last_component (name);
Packit 33f14e
  size_t length;
Packit 33f14e
Packit 33f14e
  /* If there is no last component, then name is a file system root or the
Packit 33f14e
     empty string.  */
Packit 33f14e
  if (! *base)
Packit 33f14e
    return xstrndup (name, base_len (name));
Packit 33f14e
Packit 33f14e
  /* Collapse a sequence of trailing slashes into one.  */
Packit 33f14e
  length = base_len (base);
Packit 33f14e
  if (ISSLASH (base[length]))
Packit 33f14e
    length++;
Packit 33f14e
Packit 33f14e
  /* On systems with drive letters, "a/b:c" must return "./b:c" rather
Packit 33f14e
     than "b:c" to avoid confusion with a drive letter.  On systems
Packit 33f14e
     with pure POSIX semantics, this is not an issue.  */
Packit 33f14e
  if (FILE_SYSTEM_PREFIX_LEN (base))
Packit 33f14e
    {
Packit 33f14e
      char *p = xmalloc (length + 3);
Packit 33f14e
      p[0] = '.';
Packit 33f14e
      p[1] = '/';
Packit 33f14e
      memcpy (p + 2, base, length);
Packit 33f14e
      p[length + 2] = '\0';
Packit 33f14e
      return p;
Packit 33f14e
    }
Packit 33f14e
Packit 33f14e
  /* Finally, copy the basename.  */
Packit 33f14e
  return xstrndup (base, length);
Packit 33f14e
}