Debian Codegraph @

COSMIC/fopenv.c

raw
1 /* fopenv.c : this function attempts to open a file based on the
2 * environment variable if an fopen in the current directory fails.
3 * The environment string can have ";" as separators for multiple
4 * path searching. Returns a NULL pointer if unsuccessful.
5 */
6 #include <stdio.h>
7 #include <ctype.h>
8 #include "xtdio.h"
9
10 /* -----------------------------------------------------------------------
11 * Definitions:
12 */
13 #ifdef unix
14 #define PATHSEP ':'
15 #else
16 #define PATHSEP ';'
17 #endif
18
19 /* -----------------------------------------------------------------------
20 * Source Code:
21 */
22
23 /* fopenv: opens file for read/write based on environment variable
24 * char *filename : name of file to be opened
25 * char *ctrl : "r", "w", etc.
26 * char *env_var : environment variable to be used
27 */
28 #ifdef __PROTOTYPE__
29 FILE *fopenv(
30 char *filename,
31 char *ctrl,
32 char *env_var)
33 #else /* __PROTOTYPE__ */
34 FILE *fopenv(filename,ctrl,env_var)
35 char *filename,*ctrl,*env_var;
36 #endif /* __PROTOTYPE__ */
37 {
38 char *s,*env,*buf;
39 int more;
40 FILE *fp;
41
42
43 /* see if file can be opened in current directory first */
44 fp= fopen(filename,ctrl);
45 if(fp) {
46 return fp;
47 }
48
49 /* check out the environment variable */
50 env= getenv(env_var);
51
52 /* attempt to open filename using environment search */
53 if(env) while(*env) { /* while there's environment-variable info left... */
54 for(s= env; *s && *s != PATHSEP; ++s);
55 more = *s == PATHSEP;
56 *s = '\0';
57 buf = (void *) calloc((size_t) strlen(env) + strlen(filename) + 2,sizeof(char));
58 #ifdef vms
59 sprintf(buf,"%s%s",env,filename);
60 #endif
61 #ifdef unix
62 sprintf(buf,"%s/%s",env,filename);
63 #endif
64 #ifdef LATTICE
65 sprintf(buf,"%s\\%s",env,filename);
66 #endif
67 #ifdef DESMET
68 sprintf(buf,"%s\\%s",env,filename);
69 #endif
70 #ifdef AZTEC_C
71 sprintf(buf,"%s/%s",env,filename);
72 #endif
73 #ifdef MSDOS
74 sprintf(buf,"%s\\%s",env,filename);
75 #endif
76
77 /* attempt to open file given the path */
78 fp= fopen(buf,ctrl);
79
80 /* free up memory */
81 free(buf);
82 if(fp) { /* successfully opened file */
83 return fp;
84 }
85 if(more) { /* another path to search */
86 *s= PATHSEP;
87 env= s + 1;
88 }
89 else env= s;
90 }
91
92 /* return NULL pointer, thereby indicating a modest lack of success */
93 return (FILE *) NULL;
94 }