1
0
Fork 0
C_lib/utils/file_utils.c

54 lines
1.9 KiB
C

/*
* C_lib Copyright (C) 2021 Wael Karram.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3 of the License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
/* Include header. */
#include "file_utils.h"
/* This function checks if a file or directory exists at the given path. */
static inline int check_file_exists(const char *path) {
return (path && access(path, F_OK) == 0);
}
/* This function checks if the path points to a file or directory, assumes existence! */
/* Returns 1 on file, 0 on directory, 2 for other; note that -1 indicates internal error! */
static inline int check_if_file(const char *path) {
/* Sanity check. */
assert(check_file_exists(path));
/* Check type. */
struct stat path_stat;
/* Check for failure. */
if (stat(path, &path_stat) == PASS_FAIL_FILE_UTILS_H)
return PASS_FAIL_FILE_UTILS_H;
/* Return the result. */
if (S_ISREG(path_stat.st_mode))
return TRUE_FILE_UTILS_H;
else if (S_ISDIR(path_stat.st_mode))
return FALSE_FILE_UTILS_H;
else
return OTHER_FILE_UTILS_H;
}
/* This function checks if the path exists and points to a directory. */
static inline int check_if_directory_exists(const char *path) {
return check_file_exists(path) && (check_if_file(path) == FALSE_FILE_UTILS_H);
}
/* This function checks if the path exists and points to a file. */
static inline int check_if_directory_exists(const char *path) {
return check_file_exists(path) && (check_if_file(path) == TRUE_FILE_UTILS_H);
}