Initial import of the CDE 2.1.30 sources from the Open Group.
[oweals/cde.git] / cde / programs / dtlogin / qualify.c
1 /* $XConsortium: qualify.c /main/3 1995/10/27 16:14:33 rswiston $ */
2 /*                                                                      *
3  * (c) Copyright 1993, 1994 Hewlett-Packard Company                     *
4  * (c) Copyright 1993, 1994 International Business Machines Corp.       *
5  * (c) Copyright 1993, 1994 Sun Microsystems, Inc.                      *
6  * (c) Copyright 1993, 1994 Novell, Inc.                                *
7  */
8 #include <stdio.h>
9 #include <string.h>
10
11 /*********************************************************************
12  * qualifyWithFirst
13  *
14  * takes:   an unqualified filename like foo.txt, and
15  *          a colon-separated list of pathnames, such as 
16  *                /etc/opt/dt:/opt/dt/config
17  *
18  * returns: a fully qualified filename.  Space for the filename
19  *          has been allocated off the heap.  It is the responsibility
20  *          of the calling function to dispose of the space.
21  **********************************************************************/
22
23 char * qualifyWithFirst
24   (
25   char * filename,
26   char * searchPath
27   )
28 {
29 char * paths = strdup(searchPath);
30 char * savepaths = paths;
31 char * path;
32 char * chance;
33 FILE * f;
34
35   /* assert that the arguments cannot be NULL */
36
37   if (filename == NULL || searchPath == NULL)
38     return NULL;
39
40   while (1) {
41
42     /* if there is a :, zero it */
43
44     if ((path = strchr(paths, ':')) != NULL)
45       *path = 0;
46
47     /* allocate space and create the qualified filename */
48
49     chance = (char *)malloc(strlen(paths) + strlen(filename) + 2);
50     sprintf(chance,"%s/%s",paths,filename);
51
52     /* see if it is there by opening it for reading */
53
54     if (f = fopen(chance,"r")) {
55
56       /* it's there so close it, .... */
57
58       fclose(f);
59
60       /* ... restore the colon, .... */
61
62       if (path)
63         *path = ':';
64
65       /* return the fully qualified filename */
66
67       free(savepaths);
68       return chance;
69     }
70
71     free(chance);
72
73     /* reached the end of the list of paths */
74
75     if (path == NULL)
76       break;
77
78     /* try the next path */
79
80     paths = path + 1;
81   }
82   free(savepaths);
83   return NULL;
84 }