-
Notifications
You must be signed in to change notification settings - Fork 2
/
input_parser.c
94 lines (68 loc) · 1.97 KB
/
input_parser.c
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
#include "input_parser.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
//function to free input data
void free_input_data(input_data* d) {
for (size_t i = 0; i < d->number_of_species; ++i) {
free(d->names[i]);
}
free(d->names);
free(d->matrix);
free(d);
}
//read newick tree string from empirical input example files
char* read_newk_tree(const char* newk_file) {
FILE *f = fopen(newk_file, "rb");
if (f == NULL) {
return NULL;
}
fseek(f, 0, SEEK_END);
long fsize = ftell(f);
fseek(f, 0, SEEK_SET); //same as rewind(f);
if (fsize < 0) {
fclose(f);
return NULL;
}
char *string = malloc((size_t)fsize + 1);
if (string != NULL) {
fread(string, (size_t)fsize, 1, f);
string[(size_t)fsize] = 0;
}
fclose(f);
return string;
}
//parse input data from input example files
input_data* parse_input_data(const char* data_file) {
FILE *f = fopen(data_file, "rb");
if (f == NULL) {
return NULL;
}
input_data* result = (input_data*)malloc(sizeof(input_data));
char input_buffer[256];
if (result != NULL) {
fscanf(f, "%zu %zu", &(result->number_of_species), &(result->number_of_partitions));
result->matrix = (unsigned char*)malloc(sizeof(unsigned char) * result->number_of_species * result->number_of_partitions);
result->names = (char**)malloc(sizeof(char*) * result->number_of_species);
for (size_t s = 0; s < result->number_of_species; ++s) {
for (size_t p = 0; p < result->number_of_partitions; ++p) {
fscanf(f, "%1hhu", &result->matrix[s * result->number_of_partitions + p]);
}
// discard one (whitespace)
fgetc(f);
fgets(input_buffer, 256, f);
size_t len = strlen(input_buffer);
if (len < 255) {
result->names[s] = malloc(sizeof(char) * len);
strncpy(result->names[s], input_buffer, len);
// replace newline by NULL
result->names[s][len-1] = 0;
} else {
assert(0);
}
}
}
fclose(f);
return result;
}