Always include sys/stat.h
[yaz-moved-to-github.git] / src / tpath.c
1 /*
2  * Copyright (C) 1995-2006, Index Data ApS
3  * See the file LICENSE for details.
4  *
5  * $Id: tpath.c,v 1.9 2006-04-27 08:39:05 adam Exp $
6  */
7 /**
8  * \file tpath.c
9  * \brief File Path utilities
10  */
11
12 #if HAVE_CONFIG_H
13 #include <config.h>
14 #endif
15
16
17 #include <stdio.h>
18 #include <string.h>
19 #include <ctype.h>
20 #include <yaz/tpath.h>
21 #include <yaz/log.h>
22 #include <sys/types.h>
23 #include <sys/stat.h>
24 #if HAVE_UNISTD_H
25 #include <unistd.h>
26 #endif
27
28 FILE *yaz_path_fopen(const char *path, const char *name, const char *mode)
29 {
30     return yaz_fopen (path, name, mode, 0);
31 }
32
33 int yaz_fclose (FILE *f)
34 {
35     return fclose (f);
36 }
37
38
39 char *yaz_filepath_resolve(const char *fname, const char *path,
40                            const char *base, char *fullpath)
41 {
42     for(;;)
43     {
44         struct stat stat_buf;
45         const char *path_sep = 0;
46         size_t len = 0;
47         size_t slen = 0;
48         
49         *fullpath = '\0';
50         if (path)
51         {
52             /* somewhat dirty since we have to consider Windows
53              * drive letters..
54              */
55             if (strchr ("/\\.", *path))
56             {
57                 path_sep = strchr (path+1, ':');
58             }
59             else if (path[0] && path[1])
60                 path_sep = strchr (path+2, ':');
61             if (path_sep)
62                 len = path_sep - path;
63             else
64                 len = strlen(path);
65             if (!strchr ("/\\", *path) && base)
66             {
67                 strcpy (fullpath, base);
68                 slen = strlen(fullpath);
69                 fullpath[slen++] = '/';
70             }
71             memcpy (fullpath+slen, path, len);
72             slen += len;
73             if (!strchr("/\\", fullpath[slen-1]))
74                 fullpath[slen++] = '/';
75         }
76         strcpy (fullpath+slen, fname);
77
78         if (stat(fullpath, &stat_buf) == 0)
79             return fullpath;
80         
81         if (!path_sep)
82             break;
83         path = path_sep+1;
84     }
85     return 0;
86 }
87
88 FILE *yaz_fopen(const char *path, const char *fname, const char *mode,
89                 const char *base)
90 {
91     char fullpath[1024];
92
93     if (!yaz_filepath_resolve(fname, path, base, fullpath))
94         return 0; /* failure */
95     return fopen(fullpath, mode);
96 }
97
98 int yaz_is_abspath (const char *p)
99 {
100     if (*p == '/')
101         return 1;
102 #ifdef WIN32
103     if (*p == '\\')
104         return 1;
105     if (*p && p[1] == ':' && isalpha(*p))
106         return 1;
107 #endif
108     return 0;
109 }
110 /*
111  * Local variables:
112  * c-basic-offset: 4
113  * indent-tabs-mode: nil
114  * End:
115  * vim: shiftwidth=4 tabstop=8 expandtab
116  */
117