summaryrefslogtreecommitdiff
path: root/reference/C/CONTRIB/SNIP/pfopen.c
blob: 38c7e0c48f333812476e8774a03fb65fd9714c3e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
/*
 *  Written and released to the public domain by David Engel.
 *
 *  This function attempts to open a file which may be in any of
 *  several directories.  It is particularly useful for opening
 *  configuration files.  For example, PROG.EXE can easily open
 *  PROG.CFG (which is kept in the same directory) by executing:
 *
 *      cfg_file = pfopen("PROG.CFG", "r", getenv("PATH"));
 *
 *  NULL is returned if the file can't be opened.
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#ifdef unix
 #define SEP_CHARS ":"
#else
 #define SEP_CHARS ";"
#endif

FILE *pfopen(const char *name, const char *mode, const char *dirs)
{
    char *ptr;
    char *tdirs;
    FILE *file = NULL;

    if (dirs == NULL || dirs[0] == '\0')
        return NULL;

    if ((tdirs = malloc(strlen(dirs)+1)) == NULL)
        return NULL;

    strcpy(tdirs, dirs);

    for (ptr = strtok(tdirs, SEP_CHARS); file == NULL && ptr != NULL;
        ptr = strtok(NULL, SEP_CHARS))
    {
        size_t len;
        char work[FILENAME_MAX];

        strcpy(work, ptr);
        len = strlen(work);
        if (len && work[len-1] != '/' && work[len-1] != '\\')
            strcat(work, "/");
        strcat(work, name);

        file = fopen(work, mode);
    }

    free(tdirs);

    return file;
}

#ifdef TEST

int main(int argc, char **argv)
{
    FILE *file;

    if (argc != 4)
    {
        fprintf(stderr, "usage: pfopen name mode dirs\n");
        exit(1);
    }

    file = pfopen(argv[1], argv[2], argv[3]);

    printf("%s \"%s\" with mode \"%s\"\n", (file == NULL) ?
        "Could not open" : "Opened", argv[1], argv[2]);

    return 0;
}

#endif