4 Copyright (C) 2006-2009 Jonathan Zarate
21 int f_exists(const char *path
) // note: anything but a directory
24 return (stat(path
, &st
) == 0) && (!S_ISDIR(st
.st_mode
));
27 unsigned long f_size(const char *path
) // 4GB-1 -1 = error
30 if (stat(path
, &st
) == 0) return st
.st_size
;
31 return (unsigned long)-1;
34 int f_read(const char *path
, void *buffer
, int max
)
39 if ((f
= open(path
, O_RDONLY
)) < 0) return -1;
40 n
= read(f
, buffer
, max
);
45 int f_write(const char *path
, const void *buffer
, int len
, unsigned flags
, unsigned cmode
)
47 static const char nl
= '\n';
53 if (cmode
== 0) cmode
= 0666;
54 if ((f
= open(path
, (flags
& FW_APPEND
) ? (O_WRONLY
|O_CREAT
|O_APPEND
) : (O_WRONLY
|O_CREAT
|O_TRUNC
), cmode
)) >= 0) {
55 if ((buffer
== NULL
) || ((r
= write(f
, buffer
, len
)) == len
)) {
56 if (flags
& FW_NEWLINE
) {
57 if (write(f
, &nl
, 1) == 1) ++r
;
66 int f_read_string(const char *path
, char *buffer
, int max
)
68 if (max
<= 0) return -1;
69 int n
= f_read(path
, buffer
, max
- 1);
70 buffer
[(n
> 0) ? n
: 0] = 0;
74 int f_write_string(const char *path
, const char *buffer
, unsigned flags
, unsigned cmode
)
76 return f_write(path
, buffer
, strlen(buffer
), flags
, cmode
);
79 static int _f_read_alloc(const char *path
, char **buffer
, int max
, int z
)
85 if ((n
= f_size(path
)) != (unsigned long)-1) {
87 if ((!z
) && (max
== 0)) return 0;
88 if ((*buffer
= malloc(max
+ z
)) != NULL
) {
89 if ((max
= f_read(path
, *buffer
, max
)) >= 0) {
90 if (z
) *(*buffer
+ max
) = 0;
100 int f_read_alloc(const char *path
, char **buffer
, int max
)
102 return _f_read_alloc(path
, buffer
, max
, 0);
105 int f_read_alloc_string(const char *path
, char **buffer
, int max
)
107 return _f_read_alloc(path
, buffer
, max
, 1);
111 static int _f_wait_exists(const char *name
, int max
, int invert
)
114 if (f_exists(name
) ^ invert
) return 1;
120 int f_wait_exists(const char *name
, int max
)
122 return _f_wait_exists(name
, max
, 0);
125 int f_wait_notexists(const char *name
, int max
)
127 return _f_wait_exists(name
, max
, 1);