summaryrefslogtreecommitdiff
path: root/comp/lucas-standen-NEA/code2/parser.c
blob: d9cb7bdb1219bc1b7b0312d224956b80db45d83a (plain)
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
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

#include "util.h"

typedef struct strings {
	char **strs;
	int count;
} strings;

int countChars(char *s, char c){ // counts the number of times c ocurrs in s
	int count = 0;
	for (int i = 0; i < strlen(s); i++){
		if (s[i] == c) count++;	
	}
	return count;
}

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);

			memcpy(tokens[tokCount], line, strlen(line)+1);
			charCount = 0;
			tokCount++;
		}	
	}
	strings *strs = malloc(sizeof(strings));
	strs->strs = tokens;
	strs->count = tokCount;
	
	free(line);
	free(contents);

	return strs;
}