blob: ebf8e47a8a108d734b28bf1eb568110f180c3d7f (
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
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "util.h"
int countChars(char *s, char c){
int count = 0;
for (int i = 0; i < strlen(s); i++){
if (s[i] == c) count++;
}
return count;
}
char **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++;
}
}
free(line);
free(contents);
return tokens;
}
|