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
|
#include "../include/parser.h"
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
static char* file_get_content(const char *filepath, size_t *filesize) {
struct stat file_stat;
int fd = open(filepath, O_RDONLY);
char *result = NULL;
*filesize = 0;
if(fd == -1) {
perror(filepath);
return NULL;
}
if(fstat(fd, &file_stat) == -1) {
perror(filepath);
goto cleanup;
}
if(!S_ISREG(file_stat.st_mode)) {
fprintf(stderr, "Error: %s is not a file\n", filepath);
goto cleanup;
}
*filesize = file_stat.st_size;
result = malloc(*filesize + 1);
if(!result) {
*filesize = 0;
fprintf(stderr, "Error: Failed to malloc %lu bytes from file %s\n", *filesize, filepath);
goto cleanup;
}
result[*filesize] = '\0';
if((size_t)read(fd, result, *filesize) != *filesize) {
free(result);
*filesize = 0;
fprintf(stderr, "Error: Failed to read all data from file %s\n", filepath);
goto cleanup;
}
cleanup:
close(fd);
return result;
}
static void usage() {
puts("usage: tsl [file]");
}
int main(int argc, char **argv) {
int result;
size_t filesize;
char *file_content;
if(argc != 2) {
usage();
return 1;
}
file_content = file_get_content(argv[1], &filesize);
if(!file_content)
return 1;
result = tsl_parse(file_content, filesize);
free(file_content); /* Not needed, but it make valgrind happy */
return result;
}
|