1 /*
2 * Copyright © 2011 Marcin Kościelnicki <[email protected]>
3 * All Rights Reserved.
4 * SPDX-License-Identifier: MIT
5 */
6
7 #include "util.h"
8 #include <string.h>
9
find_in_path(const char * name,const char * path,char ** pfullname)10 FILE *find_in_path(const char *name, const char *path, char **pfullname) {
11 if (!path)
12 return 0;
13 while (path) {
14 const char *npath = strchr(path, ':');
15 size_t plen;
16 if (npath) {
17 plen = npath - path;
18 npath++;
19 } else {
20 plen = strlen(path);
21 }
22 if (plen) {
23 /* also look for .gz compressed xml: */
24 const char *exts[] = { "", ".gz" };
25 for (int i = 0; i < ARRAY_SIZE(exts); i++) {
26 char *fullname;
27
28 int ret = asprintf(&fullname, "%.*s/%s%s", (int)plen, path, name, exts[i]);
29 if (ret < 0)
30 return NULL;
31
32 FILE *file = fopen(fullname, "r");
33 if (file) {
34 if (pfullname)
35 *pfullname = fullname;
36 else
37 free(fullname);
38 return file;
39 }
40 free(fullname);
41 }
42 }
43 path = npath;
44 }
45 return 0;
46 }
47