BRL-CAD
dirent.c
Go to the documentation of this file.
1 /* D I R E N T . C
2  * BRL-CAD
3  *
4  * Copyright (c) 2001-2014 United States Government as represented by
5  * the U.S. Army Research Laboratory.
6  *
7  * This library is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public License
9  * version 2.1 as published by the Free Software Foundation.
10  *
11  * This library is distributed in the hope that it will be useful, but
12  * WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with this file; see the file named COPYING for more
18  * information.
19  */
20 
21 #include "common.h"
22 
23 #include <stdio.h>
24 #include <stdlib.h>
25 #include <string.h>
26 #include <sys/types.h>
27 
28 #include "bu/file.h"
29 #include "bu/malloc.h"
30 #include "bu/str.h"
31 #include "uce-dirent.h"
32 
33 size_t
34 bu_dir_list(const char *path, const char *pattern, char ***files)
35 {
36  size_t i = 0;
37  size_t filecount = 0;
38  DIR *dir = NULL;
39  struct dirent *dp = NULL;
40 
41  /* calculate file cound */
42  dir = opendir(path);
43  while ((dp = readdir(dir)) != NULL) {
44  if (!pattern
45  || (strlen(pattern) == 0)
46  || (bu_fnmatch(pattern, dp->d_name, 0) == 0))
47  {
48  filecount++;
49  }
50  }
51  (void)closedir(dir);
52 
53  /* bail now if there's no files array pointer to fill in */
54  if (!files) {
55  return filecount;
56  }
57 
58  /* allocate enough space plus room for a null entry too */
59  *files = (char **)bu_calloc(filecount+1, sizeof(char *), "files alloc");
60 
61  dir = opendir(path);
62  while ((dp = readdir(dir)) != NULL) {
63  if (!pattern
64  || (strlen(pattern) == 0)
65  || (bu_fnmatch(pattern, dp->d_name, 0) == 0))
66  {
67  (*files)[i++] = bu_strdup(dp->d_name);
68  }
69  }
70  (void)closedir(dir);
71 
72  return filecount;
73 }
74 
75 
76 /*
77  * Local Variables:
78  * mode: C
79  * tab-width: 8
80  * indent-tabs-mode: t
81  * c-file-style: "stroustrup"
82  * End:
83  * ex: shiftwidth=4 tabstop=8
84  */
Header file for the BRL-CAD common definitions.
void * bu_calloc(size_t nelem, size_t elsize, const char *str)
Definition: malloc.c:321
int bu_fnmatch(const char *pattern, const char *pathname, int flags)
Definition: fnmatch.c:311
size_t bu_dir_list(const char *path, const char *pattern, char ***files)
Definition: dirent.c:34
#define bu_strdup(s)
Definition: str.h:71