New functions yaz_is_abspath, yaz_path_fopen_base
[yaz-moved-to-github.git] / util / tpath.c
1 /*
2  * Copyright (c) 1995-2002, Index Data.
3  * See the file LICENSE for details.
4  * Sebastian Hammer, Adam Dickmeiss
5  *
6  * $Id: tpath.c,v 1.6 2002-04-04 20:49:46 adam Exp $
7  */
8 #if HAVE_CONFIG_H
9 #include <config.h>
10 #endif
11
12
13 #include <stdio.h>
14 #include <string.h>
15 #include <ctype.h>
16 #include <yaz/tpath.h>
17 #include <yaz/log.h>
18
19 FILE *yaz_path_fopen(const char *path, const char *name, const char *mode)
20 {
21     return yaz_path_fopen_base (path, name, mode, 0);
22 }
23
24 FILE *yaz_path_fopen_base(const char *path, const char *name, const char *mode,
25                           const char *base)
26 {
27     char spath[1024];
28
29     for(;;)
30     {
31         FILE *f;
32
33         const char *path_sep = 0;
34         size_t len = 0;
35         size_t slen = 0;
36         
37         *spath = '\0';
38         if (path)
39         {
40             /* somewhat dirty since we have to consider Windows
41              * drive letters..
42              */
43             if (strchr ("/\\.", *path))
44             {
45                 path_sep = strchr (path+1, ':');
46             }
47             else if (path[0] && path[1])
48                 path_sep = strchr (path+2, ':');
49             if (path_sep)
50                 len = path_sep - path;
51             else
52                 len = strlen(path);
53             if (!strchr ("/\\", *path) && base)
54             {
55                 strcpy (spath, base);
56                 slen = strlen(spath);
57                 spath[slen++] = '/';
58             }
59             memcpy (spath+slen, path, len);
60             slen += len;
61             if (!strchr("/\\", spath[slen-1]))
62                 spath[slen++] = '/';
63         }
64         strcpy (spath+slen, name);
65         if ((f = fopen(spath, mode)))
66             return f;
67         
68         if (!path_sep)
69             break;
70         path = path_sep+1;
71     }
72     return 0;
73 }
74
75 int yaz_is_abspath (const char *p)
76 {
77     if (*p == '/')
78         return 1;
79 #ifdef WIN32
80     if (*p == '\\')
81         return 1;
82     if (*p && p[1] == ':' && isalpha(*p))
83         return 1;
84 #endif
85     return 0;
86 }