From 1d698418c785a227f00bffd13db29d5182ba1829 Mon Sep 17 00:00:00 2001 From: Joachim Nilsson Date: Mon, 6 Jun 2016 17:52:06 +0200 Subject: [PATCH] dir(): Do not assert(), return -1 and errno The dir() function, although useless compared to glob(), called assert() and perror() instead of returning an error code. Signed-off-by: Joachim Nilsson --- README.md | 3 ++- dir.c | 21 +++++++++++++-------- 2 files changed, 15 insertions(+), 9 deletions(-) diff --git a/README.md b/README.md index 649659f..d013c81 100644 --- a/README.md +++ b/README.md @@ -155,7 +155,8 @@ Generic Functions Wrapper for `scandir()` with optional filter. Returns a list of names: files and directories that must be freed after use. See - the unit test at the bottom for an example. + the unit test for an example, or take a look at `glob(3)`, it's + probably what you want anyway. - `fcopyfile(src, dst)` diff --git a/dir.c b/dir.c index ac623d7..0e5f5d0 100644 --- a/dir.c +++ b/dir.c @@ -1,6 +1,6 @@ /* Functions for operating on files in directories. * - * Copyright (c) 2008-2014 Joachim Nilsson + * Copyright (c) 2008-2016 Joachim Nilsson * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above @@ -15,14 +15,14 @@ * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ -#include +#include #include -#include #include #include static const char *matcher_type = NULL; static int (*matcher_filter) (const char *file) = NULL; + static int matcher(const struct dirent *entry) { char *pos = strrchr(entry->d_name, '.'); @@ -72,7 +72,8 @@ static int matcher(const struct dirent *entry) * would be returned as "config0". * * Returns: - * Number of files in @list, zero if no matching files of @type. + * Number of files in @list, zero if no matching files of @type, or + * non-zero on error with @errno set. */ int dir(const char *dir, const char *type, int (*filter) (const char *file), char ***list, int strip) { @@ -80,7 +81,10 @@ int dir(const char *dir, const char *type, int (*filter) (const char *file), cha char **files; struct dirent **namelist; - assert(list); + if (!list) { + errno = EINVAL; + return -1; + } if (!dir) /* Assuming current directory */ @@ -92,9 +96,10 @@ int dir(const char *dir, const char *type, int (*filter) (const char *file), cha matcher_type = type; matcher_filter = filter; n = scandir(dir, &namelist, matcher, alphasort); - if (n < 0) { - perror("scandir"); - } else if (n > 0) { + if (n < 0) + return -1; + + if (n > 0) { files = (char **)malloc(n * sizeof(char *)); for (i = 0; i < n; i++) { if (files) {