1249259Sdim/* Construct a full pathname from a directory and a filename.
2249259Sdim   Copyright (C) 2001-2004, 2006 Free Software Foundation, Inc.
3249259Sdim
4249259Sdim   This program is free software; you can redistribute it and/or modify it
5249259Sdim   under the terms of the GNU General Public License as published by the
6249259Sdim   Free Software Foundation; either version 2, or (at your option) any
7249259Sdim   later version.
8249259Sdim
9249259Sdim   This program is distributed in the hope that it will be useful,
10249259Sdim   but WITHOUT ANY WARRANTY; without even the implied warranty of
11249259Sdim   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12249259Sdim   GNU General Public License for more details.
13249259Sdim
14249259Sdim   You should have received a copy of the GNU General Public License
15249259Sdim   along with this program; if not, write to the Free Software
16249259Sdim   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
17249259Sdim   USA.  */
18249259Sdim
19249259Sdim/* Written by Bruno Haible <haible@clisp.cons.org>.  */
20249259Sdim
21249259Sdim#include <config.h>
22249259Sdim
23249259Sdim/* Specification.  */
24249259Sdim#include "pathname.h"
25266715Sdim
26266715Sdim#include <string.h>
27266715Sdim
28266715Sdim#include "xalloc.h"
29266715Sdim#include "stpcpy.h"
30266715Sdim
31266715Sdim/* 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