| 1 | /* Construct a full filename from a directory and a relative filename. |
| 2 | Copyright (C) 2001-2004, 2006-2020 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 <https://www.gnu.org/licenses/>. */ |
| 16 | |
| 17 | /* Written by Bruno Haible <[email protected]>. */ |
| 18 | |
| 19 | #include <config.h> |
| 20 | |
| 21 | /* Specification. */ |
| 22 | #include "concat-filename.h" |
| 23 | |
| 24 | #include <errno.h> |
| 25 | #include <stdlib.h> |
| 26 | #include <string.h> |
| 27 | |
| 28 | #include "filename.h" |
| 29 | |
| 30 | /* Concatenate a directory filename, a relative filename 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 filename. Return NULL and set errno |
| 34 | upon memory allocation failure. */ |
| 35 | char * |
| 36 | concatenated_filename (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 *) malloc (strlen (filename) |
| 46 | + (suffix != NULL ? strlen (suffix) : 0) |
| 47 | + 1); |
| 48 | if (result == NULL) |
| 49 | return NULL; /* errno is set here */ |
| 50 | p = result; |
| 51 | } |
| 52 | else |
| 53 | { |
| 54 | size_t directory_len = strlen (directory); |
| 55 | int need_slash = |
| 56 | (directory_len > FILE_SYSTEM_PREFIX_LEN (directory) |
| 57 | && !ISSLASH (directory[directory_len - 1])); |
| 58 | result = (char *) malloc (directory_len + need_slash |
| 59 | + strlen (filename) |
| 60 | + (suffix != NULL ? strlen (suffix) : 0) |
| 61 | + 1); |
| 62 | if (result == NULL) |
| 63 | return NULL; /* errno is set here */ |
| 64 | memcpy (result, directory, directory_len); |
| 65 | p = result + directory_len; |
| 66 | if (need_slash) |
| 67 | *p++ = '/'; |
| 68 | } |
| 69 | p = stpcpy (p, filename); |
| 70 | if (suffix != NULL) |
| 71 | stpcpy (p, suffix); |
| 72 | return result; |
| 73 | } |