diff options
author | JSDurand <mmemmew@gmail.com> | 2022-01-04 11:51:58 +0800 |
---|---|---|
committer | JSDurand <mmemmew@gmail.com> | 2022-01-04 11:51:58 +0800 |
commit | 55dc897da6e81f2a26cfc7e66ac942824773498b (patch) | |
tree | fce0d7d57832907c991d551833bf5eecde947dd2 /src/util.c | |
parent | 53b8b6ffab5a968db75e9babddf4e2dbb2c688a3 (diff) |
temporary commit
Now we can read grammars from a file.
But we need to check if it works for reading strings still.
Diffstat (limited to 'src/util.c')
-rw-r--r-- | src/util.c | 49 |
1 files changed, 49 insertions, 0 deletions
diff --git a/src/util.c b/src/util.c new file mode 100644 index 0000000..e228fbb --- /dev/null +++ b/src/util.c @@ -0,0 +1,49 @@ +#include <stdlib.h> +#include <stdio.h> +#include "util.h" + +/* Put the entire file content into the string str and the file size + into *len. + + If errors occur, return non-zero; otherwise the return value is + zero. + + Note that *str should be already allocated. + + Note that the length of the string str is actually 1+length, and + the last character is the null character. */ +unsigned char +read_entire_file(const char *file_name, char **str, NUM *len) +{ + long file_size = 0; + + FILE *file = fopen(file_name, "r"); + + if (!file) { + eprintf("%s:%d, Cannot open file \"%s\": ", + __FILE__, __LINE__, file_name); + perror(NULL); + return 1; + } + + fseek(file, 0, SEEK_END); + file_size = ftell(file); + fseek(file, 0, SEEK_SET); + + *len = 1+file_size; + + *str = realloc(*str, 1+file_size); + + if (*str == NULL) { + fleprintf0("%s:%d, Cannot realloc\n"); + return 1; + } + + fread(*str, sizeof(char), file_size, file); + + fclose(file); + + *(*str+file_size) = 0; + + return 0; +} |