diff options
Diffstat (limited to 'comp/lucas-standen-NEA/code2/parser.c')
-rw-r--r-- | comp/lucas-standen-NEA/code2/parser.c | 45 |
1 files changed, 12 insertions, 33 deletions
diff --git a/comp/lucas-standen-NEA/code2/parser.c b/comp/lucas-standen-NEA/code2/parser.c index d9cb7bd..7650c4f 100644 --- a/comp/lucas-standen-NEA/code2/parser.c +++ b/comp/lucas-standen-NEA/code2/parser.c @@ -19,41 +19,20 @@ int countChars(char *s, char c){ // counts the number of times c ocurrs in s } strings *parse(FILE *f){ - fseek(f, 0, SEEK_END); - int len = ftell(f); - rewind(f); - - char *contents = malloc(len); - - if (fread(contents, 1, len, f) == 0){ - die("failed to read file, is it formated properly"); - } - - char **tokens = malloc(countChars(contents, '\n')); - - int tokCount = 0; - int charCount = 0; - char *line = malloc(strlen(contents)); - for (int i = 0; i < len; i++){ - line[charCount] = contents[i]; - charCount++; - - if (contents[i] == '\n'){ - charCount--; - line[charCount] = '\0'; - tokens[tokCount] = malloc(strlen(line)+1); + strings *strs = malloc(sizeof(strings)); + strs->strs = malloc(sizeof(char **)); - memcpy(tokens[tokCount], line, strlen(line)+1); - charCount = 0; - tokCount++; - } + char *line = alloca(256); + int count = 0; + while (fgets(line, 256, f) != NULL){ + if (line[0] != '\n'){ + line[strlen(line)-1] = '\0'; + strs->strs[count] = malloc(256); + memcpy(strs->strs[count], line, 256); + count++; + } } - strings *strs = malloc(sizeof(strings)); - strs->strs = tokens; - strs->count = tokCount; - - free(line); - free(contents); + strs->count = count; return strs; } |