concat-filename.c 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. /* Construct a full filename from a directory and a relative filename.
  2. Copyright (C) 2001-2004, 2006-2013 Free Software Foundation, Inc.
  3. This program is free software: you can redistribute it and/or modify it
  4. under the terms of the GNU General Public License as published by the
  5. Free Software Foundation; either version 3 of the License, or any
  6. later version.
  7. This program is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU General Public License for more details.
  11. You should have received a copy of the GNU General Public License
  12. along with this program. If not, see <http://www.gnu.org/licenses/>. */
  13. /* Written by Bruno Haible <haible@clisp.cons.org>. */
  14. #include <config.h>
  15. /* Specification. */
  16. #include "concat-filename.h"
  17. #include <errno.h>
  18. #include <stdlib.h>
  19. #include "string--.h"
  20. #include "filename.h"
  21. /* Concatenate a directory filename, a relative filename and an optional
  22. suffix. The directory may end with the directory separator. The second
  23. argument may not start with the directory separator (it is relative).
  24. Return a freshly allocated filename. Return NULL and set errno
  25. upon memory allocation failure. */
  26. char *
  27. concatenated_filename (const char *directory, const char *filename,
  28. const char *suffix)
  29. {
  30. char *result;
  31. char *p;
  32. if (strcmp (directory, ".") == 0)
  33. {
  34. /* No need to prepend the directory. */
  35. result = (char *) malloc (strlen (filename)
  36. + (suffix != NULL ? strlen (suffix) : 0)
  37. + 1);
  38. if (result == NULL)
  39. return NULL; /* errno is set here */
  40. p = result;
  41. }
  42. else
  43. {
  44. size_t directory_len = strlen (directory);
  45. int need_slash =
  46. (directory_len > FILE_SYSTEM_PREFIX_LEN (directory)
  47. && !ISSLASH (directory[directory_len - 1]));
  48. result = (char *) malloc (directory_len + need_slash
  49. + strlen (filename)
  50. + (suffix != NULL ? strlen (suffix) : 0)
  51. + 1);
  52. if (result == NULL)
  53. return NULL; /* errno is set here */
  54. memcpy (result, directory, directory_len);
  55. p = result + directory_len;
  56. if (need_slash)
  57. *p++ = '/';
  58. }
  59. p = stpcpy (p, filename);
  60. if (suffix != NULL)
  61. stpcpy (p, suffix);
  62. return result;
  63. }