*** empty log message ***
[gnulib.git] / lib / concatpath.c
1 /* Construct a full pathname from a directory and a filename.
2    Copyright (C) 2001-2004 Free Software Foundation, Inc.
3
4    This program is free software; you can redistribute it and/or modify it
5    under the terms of the GNU General Public License as published by the
6    Free Software Foundation; either version 2, or (at your option) any
7    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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
17    USA.  */
18
19 /* Written by Bruno Haible <haible@clisp.cons.org>.  */
20
21 #ifdef HAVE_CONFIG_H
22 # include <config.h>
23 #endif
24
25 /* Specification.  */
26 #include "pathname.h"
27
28 #include <string.h>
29
30 #include "xalloc.h"
31 #include "stpcpy.h"
32
33 /* Concatenate a directory pathname, a relative pathname and an optional
34    suffix.  The directory may end with the directory separator.  The second
35    argument may not start with the directory separator (it is relative).
36    Return a freshly allocated pathname.  */
37 char *
38 concatenated_pathname (const char *directory, const char *filename,
39                        const char *suffix)
40 {
41   char *result;
42   char *p;
43
44   if (strcmp (directory, ".") == 0)
45     {
46       /* No need to prepend the directory.  */
47       result = (char *) xmalloc (strlen (filename)
48                                  + (suffix != NULL ? strlen (suffix) : 0)
49                                  + 1);
50       p = result;
51     }
52   else
53     {
54       size_t directory_len = strlen (directory);
55       int need_slash =
56         (directory_len > FILE_SYSTEM_PREFIX_LEN (directory)
57          && !ISSLASH (directory[directory_len - 1]));
58       result = (char *) xmalloc (directory_len + need_slash
59                                  + strlen (filename)
60                                  + (suffix != NULL ? strlen (suffix) : 0)
61                                  + 1);
62       memcpy (result, directory, directory_len);
63       p = result + directory_len;
64       if (need_slash)
65         *p++ = '/';
66     }
67   p = stpcpy (p, filename);
68   if (suffix != NULL)
69     stpcpy (p, suffix);
70   return result;
71 }