forked from lh3/treebest
-
Notifications
You must be signed in to change notification settings - Fork 8
/
read.c
45 lines (42 loc) · 1013 Bytes
/
read.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
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include "tree.h"
Matrix *tr_read_matrix(FILE *fp)
{
int i, j, n;
char name[256];
Matrix *mat;
double x;
assert(fp);
fscanf(fp, "%d", &n);
mat = (Matrix*)malloc(sizeof(Matrix));
mat->count = n;
mat->dist = (double*)malloc(sizeof(double) * mat->count * mat->count);
mat->name = (char**)malloc(sizeof(char*) * mat->count);
for (i = 0; i < mat->count; ++i) {
if (fscanf(fp, "%s", name) == 0) {
fprintf(stderr, "[tr_read_matrix] fail to read distance matrix\n");
tr_delete_matrix(mat);
return 0;
}
mat->name[i] = (char*)malloc(sizeof(char) * (strlen(name) + 1));
strcpy(mat->name[i], name);
for (j = 0; j < mat->count; ++j) {
fscanf(fp, "%lf", &x);
mat->dist[j * mat->count + i] = x;
}
mat->dist[i * mat->count + i] = 0.0;
}
return mat;
}
void tr_delete_matrix(Matrix *mat)
{
int i;
if (mat == 0) return;
free(mat->dist);
for (i = 0; i < mat->count; ++i)
free(mat->name[i]);
free(mat->name);
free(mat);
}