BRL-CAD
basename.c
Go to the documentation of this file.
1 /* B A S E N A M E . C
2  * BRL-CAD
3  *
4  * Copyright (c) 2004-2014 United States Government as represented by
5  * the U.S. Army Research Laboratory.
6  *
7  * This library is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public License
9  * version 2.1 as published by the Free Software Foundation.
10  *
11  * This library is distributed in the hope that it will be useful, but
12  * WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with this file; see the file named COPYING for more
18  * information.
19  */
20 
21 #include "common.h"
22 
23 #include <string.h>
24 #include <ctype.h>
25 
26 #include "bu/log.h"
27 #include "bu/str.h"
28 
29 void
30 bu_basename(char *basename, const char *path)
31 {
32  const char *p;
33  size_t len;
34 
35  if (UNLIKELY(!path)) {
36  bu_strlcpy(basename, ".", strlen(".")+1);
37  return;
38  }
39 
40  /* skip the filesystem disk/drive name if we're on a DOS-capable
41  * platform that uses '\' for paths, e.g., C:\ -> \
42  */
43  if (BU_DIR_SEPARATOR == '\\' && isalpha((int)(path[0])) && path[1] == ':') {
44  path += 2;
45  }
46 
47  /* Skip leading separators, e.g., ///foo/bar -> foo/bar */
48  for (p = path; *p != '\0'; p++) {
49  /* check native separator as well as / so we can use this
50  * routine for geometry paths too.
51  */
52  if ((p[0] == BU_DIR_SEPARATOR && p[1] != BU_DIR_SEPARATOR && p[1] != '\0')
53  || (p[0] == '/' && p[1] != '/' && p[1] != '\0')) {
54  path = p+1;
55  }
56  }
57 
58  len = strlen(path);
59 
60  /* Remove trailing separators */
61  while (len > 1 && (path[len - 1] == BU_DIR_SEPARATOR || path[len - 1] == '/'))
62  len--;
63 
64  if (len > 0) {
65  bu_strlcpy(basename, path, len+1);
66  } else {
67  basename[0] = '.';
68  }
69 }
70 
71 /*
72  * Local Variables:
73  * mode: C
74  * tab-width: 8
75  * indent-tabs-mode: t
76  * c-file-style: "stroustrup"
77  * End:
78  * ex: shiftwidth=4 tabstop=8
79  */
Header file for the BRL-CAD common definitions.
#define bu_strlcpy(dst, src, size)
Definition: str.h:60
#define BU_DIR_SEPARATOR
Definition: defines.h:97
void bu_basename(char *basename, const char *path)
Definition: basename.c:30
#define UNLIKELY(expression)
Definition: common.h:282