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