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