-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathutils.c
90 lines (68 loc) · 1.63 KB
/
utils.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
/* Misc functions - strings etc */
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include "utils.h"
/* FIXME: vasprintf is a GNU extension, so it maybe
* has to be rewritten in platform-independent way ?
*/
char *make_string(const char *template, ...)
{
va_list ap;
char *buffer;
va_start(ap, template);
vasprintf(&buffer, template, ap);
va_end(ap);
return buffer;
}
void add_to_string(char **string, char *add)
{
int length = (string && *string) ? strlen(*string) : 0;
*string = realloc(*string, length + strlen(add) + 1);
memcpy((char *)*string + length, add, strlen(add) + 1);
}
void add_pattern_to_string(char **string, const char *template,
...)
{
va_list ap;
char *buffer;
va_start(ap, template);
vasprintf(&buffer, template, ap);
va_end(ap);
add_to_string(string, buffer);
if(buffer)
free(buffer);
}
int file_exists_and_normal(char *filename)
{
struct stat status;
int result = !stat(filename, &status);
if(result && !S_ISREG(status.st_mode) && !S_ISLNK(status.st_mode))
result = FALSE;
if(result && access(filename, R_OK)) {
result = FALSE;
}
return result;
}
char *file_read_string(FILE *file)
{
char *string = NULL;
int max_length = 0;
int length = 0;
while(!feof(file)){
int current = fgetc(file);
if(current == EOF || current == '\n')
break;
if(length == max_length){
max_length += 1024;
string = realloc(string, max_length + 1);
}
string[length] = current;
string[length + 1] = '\0';
length ++;
}
/* FIXME: memory allocated is larger than string length here */
/* But it will be freed, so it is not critical */
return string;
}