tilesets
[vrlugburz] / src / fs.c
1 #include <stdio.h>
2 #include <string.h>
3 #include <alloca.h>
4 #include "fs.h"
5
6 char *path_dir(const char *path, char *buf)
7 {
8         char *sep;
9
10         if(!buf) buf = (char*)path;
11         if(path != buf) {
12                 strcpy(buf, path);
13         }
14
15         if((sep = strrchr(buf, '/')) && sep > buf) {
16                 *sep = 0;
17         }
18         return buf;
19 }
20
21 char *path_file(const char *path, char *buf)
22 {
23         int len;
24         char *sep;
25
26         if(!buf) buf = (char*)path;
27         if(path != buf) {
28                 strcpy(buf, path);
29         }
30
31         if((sep = strrchr(buf, '/'))) {
32                 len = strlen(sep + 1);
33                 memmove(buf, sep + 1, len + 1);
34         }
35         return buf;
36 }
37
38 char *combine_path(const char *dirname, const char *fname, char *buf)
39 {
40         char *dest;
41
42         if(!buf) return 0;
43
44         if(!dirname || !*dirname) {
45                 strcpy(buf, fname);
46                 return buf;
47         }
48
49         dest = buf;
50         while(*dirname) *dest++ = *dirname++;
51
52         if(dest[-1] != '/') *dest++ = '/';
53
54         strcpy(dest, fname);
55         return buf;
56 }
57
58 FILE *fopenat(const char *dirname, const char *fname, const char *attr)
59 {
60         char *buf;
61
62         if(!dirname || !*dirname) {
63                 return fopen(fname, attr);
64         }
65
66         buf = alloca(strlen(dirname) + strlen(fname) + 2);
67         combine_path(dirname, fname, buf);
68         return fopen(buf, attr);
69 }