00001 /* 00002 * Copyright 2008, 2009 Alexandros Frantzis, Michael Iatrou 00003 * 00004 * This file is part of libbls. 00005 * 00006 * libbls is free software: you can redistribute it and/or modify it under the 00007 * terms of the GNU Lesser General Public License as published by the Free 00008 * Software Foundation, either version 3 of the License, or (at your option) 00009 * any later version. 00010 * 00011 * libbls is distributed in the hope that it will be useful, but WITHOUT ANY 00012 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS 00013 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more 00014 * details. 00015 * 00016 * You should have received a copy of the GNU General Public License along with 00017 * libbls. If not, see <http://www.gnu.org/licenses/>. 00018 */ 00019 00020 /** 00021 * @file util.c 00022 * 00023 * Implementation of utility functions used by libbls. 00024 */ 00025 00026 #include <stdlib.h> 00027 #include <string.h> 00028 #include <errno.h> 00029 #include <sys/types.h> 00030 00031 #include "debug.h" 00032 #include "util.h" 00033 00034 /** 00035 * Joins two path components to form a full path. 00036 * 00037 * The resulting path should be freed using free() when it is not needed 00038 * anymore. 00039 * 00040 * @param[out] result the resulting combined path 00041 * @param path1 first path component 00042 * @param path2 second path component 00043 * 00044 * @return the operation error code 00045 */ 00046 int path_join(char **result, char *path1, char *path2) 00047 { 00048 if (result == NULL || path1 == NULL || path2 == NULL) 00049 return_error(EINVAL); 00050 00051 /* TODO: Path separator depends on platform! */ 00052 char *sep = "/"; 00053 int need_sep = 0; 00054 00055 size_t result_size = strlen(path1) + strlen(path2) + 1; 00056 00057 /* Check if we need to add a path separator between the two components. */ 00058 if (path1[strlen(path1) - 1] != sep[0]) { 00059 need_sep = 1; 00060 result_size += 1; 00061 } 00062 00063 *result = malloc(result_size); 00064 if (*result == NULL) 00065 return_error(ENOMEM); 00066 00067 strncpy(*result, path1, result_size); 00068 00069 if (need_sep == 1) 00070 strncat(*result, sep, result_size - strlen(*result) - 1); 00071 00072 strncat(*result, path2, result_size - strlen(*result) - 1); 00073 00074 return 0; 00075 } 00076