Move to here from concatpath.c.
[gnulib.git] / lib / concat-filename.c
1 /* Construct a full pathname from a directory and a filename.
2    Copyright (C) 2001-2004, 2006, 2007 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 #include <config.h>
22
23 /* Specification.  */
24 #include "pathname.h"
25
26 #include <string.h>
27
28 #include "xalloc.h"
29
30 /* Concatenate a directory pathname, a relative pathname and an optional
31    suffix.  The directory may end with the directory separator.  The second
32    argument may not start with the directory separator (it is relative).
33    Return a freshly allocated pathname.  */
34 char *
35 concatenated_pathname (const char *directory, const char *filename,
36                        const char *suffix)
37 {
38   char *result;
39   char *p;
40
41   if (strcmp (directory, ".") == 0)
42     {
43       /* No need to prepend the directory.  */
44       result = XNMALLOC (strlen (filename)
45                          + (suffix != NULL ? strlen (suffix) : 0)
46                          + 1,
47                          char);
48       p = result;
49     }
50   else
51     {
52       size_t directory_len = strlen (directory);
53       int need_slash =
54         (directory_len > FILE_SYSTEM_PREFIX_LEN (directory)
55          && !ISSLASH (directory[directory_len - 1]));
56       result = XNMALLOC (directory_len + need_slash
57                          + strlen (filename)
58                          + (suffix != NULL ? strlen (suffix) : 0)
59                          + 1,
60                          char);
61       memcpy (result, directory, directory_len);
62       p = result + directory_len;
63       if (need_slash)
64         *p++ = '/';
65     }
66   p = stpcpy (p, filename);
67   if (suffix != NULL)
68     stpcpy (p, suffix);
69   return result;
70 }