1/* Construct a full pathname from a directory and a filename.
2   Copyright (C) 2001-2004, 2006 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#include "stpcpy.h"
30
31/* Concatenate a directory pathname, a relative pathname and an optional
32   suffix.  The directory may end with the directory separator.  The second
33   argument may not start with the directory separator (it is relative).
34   Return a freshly allocated pathname.  */
35char *
36concatenated_pathname (const char *directory, const char *filename,
37		       const char *suffix)
38{
39  char *result;
40  char *p;
41
42  if (strcmp (directory, ".") == 0)
43    {
44      /* No need to prepend the directory.  */
45      result = (char *) xmalloc (strlen (filename)
46				 + (suffix != NULL ? strlen (suffix) : 0)
47				 + 1);
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 = (char *) xmalloc (directory_len + need_slash
57				 + strlen (filename)
58				 + (suffix != NULL ? strlen (suffix) : 0)
59				 + 1);
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}
70