File: fopenv.c

package info (click to toggle)
robotour 3.1.1-1
  • links: PTS
  • area: main
  • in suites: sarge
  • size: 2,596 kB
  • ctags: 2,972
  • sloc: cpp: 17,705; sh: 3,060; ansic: 2,778; makefile: 144
file content (94 lines) | stat: -rwxr-xr-x 2,174 bytes parent folder | download
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
/* fopenv.c : this function attempts to open a file based on the
 *   environment variable if an fopen in the current directory fails.
 *   The environment string can have ";" as separators for multiple
 *   path searching.  Returns a NULL pointer if unsuccessful.
 */
#include <stdio.h>
#include <ctype.h>
#include "xtdio.h"

/* -----------------------------------------------------------------------
 * Definitions:
 */
#ifdef unix
#define PATHSEP ':'
#else
#define PATHSEP ';'
#endif

/* -----------------------------------------------------------------------
 * Source Code:
 */

/* fopenv: opens file for read/write based on environment variable
 *	char *filename : name of file to be opened
 *	char *ctrl     : "r", "w", etc.
 *	char *env_var  : environment variable to be used
 */
#ifdef __PROTOTYPE__
FILE *fopenv(
  char *filename,
  char *ctrl,
  char *env_var)
#else	/* __PROTOTYPE__ */
FILE *fopenv(filename,ctrl,env_var)
char *filename,*ctrl,*env_var;
#endif	/* __PROTOTYPE__ */
{
char *s,*env,*buf;
int more;
FILE *fp;


/* see if file can be opened in current directory first */
fp= fopen(filename,ctrl);
if(fp) {
	return fp;
	}

/* check out the environment variable */
env= getenv(env_var);

/* attempt to open filename using environment search */
if(env) while(*env) { /* while there's environment-variable info left... */
	for(s= env; *s && *s != PATHSEP; ++s);
	more= *s == PATHSEP;
	*s  = '\0';
	buf= calloc((size_t) strlen(env) + strlen(filename) + 2,sizeof(char));
#ifdef vms
	sprintf(buf,"%s%s",env,filename);
#endif
#ifdef unix
	sprintf(buf,"%s/%s",env,filename);
#endif
#ifdef LATTICE
	sprintf(buf,"%s\\%s",env,filename);
#endif
#ifdef DESMET
	sprintf(buf,"%s\\%s",env,filename);
#endif
#ifdef AZTEC_C
	sprintf(buf,"%s/%s",env,filename);
#endif
#ifdef MSDOS
	sprintf(buf,"%s\\%s",env,filename);
#endif

	/* attempt to open file given the path */
	fp= fopen(buf,ctrl);

	/* free up memory */
	free(buf);
	if(fp) { /* successfully opened file */
		return fp;
		}
	if(more) {	/* another path to search */
		*s= PATHSEP;
		env= s + 1;
		}
	else env= s;
	}

/* return NULL pointer, thereby indicating a modest lack of success */
return (FILE *) NULL;
}