-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathio.c
100 lines (79 loc) · 1.77 KB
/
io.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
95
96
97
98
99
100
#include "io.h"
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <assert.h>
double* read_points(FILE *f, int* n_out, int *d_out) {
int read;
int32_t n, d;
read = fread(&n, sizeof(int32_t), 1, f);
if (read != 1) {
return NULL;
}
read = fread(&d, sizeof(int32_t), 1, f);
if (read != 1) {
return NULL;
}
double* data = malloc(n*d*sizeof(double));
read = fread(data, d*sizeof(double), n, f);
if (read != n) {
free(data);
return NULL;
} else {
*n_out = n;
*d_out = d;
return data;
}
}
int* read_indexes(FILE *f, int *n_out, int *k_out) {
int read;
int32_t n, k;
read = fread(&n, sizeof(int32_t), 1, f);
if (read != 1) {
return NULL;
}
read = fread(&k, sizeof(int32_t), 1, f);
if (read != 1) {
return NULL;
}
int* data = malloc(n*k*sizeof(int));
read = fread(data, k*sizeof(int), n, f);
if (read != n) {
free(data);
return NULL;
} else {
*n_out = n;
*k_out = k;
return data;
}
}
int write_points(FILE *f, int32_t n, int32_t d, double *data) {
// Write number of points.
if (fwrite(&n, sizeof(int32_t), 1, f) != 1) {
return 1;
}
// Write number of values for each point (dimensionality).
if (fwrite(&d, sizeof(int32_t), 1, f) != 1) {
return 1;
}
// Write the raw point data.
if ((int)fwrite(data, d*sizeof(double), n, f) != n) {
return 1;
}
return 0;
}
int write_indexes(FILE *f, int32_t n, int32_t k, int *data) {
// Write number of points.
if (fwrite(&n, sizeof(int32_t), 1, f) != 1) {
return 1;
}
// Write number of indexes for each point.
if (fwrite(&k, sizeof(int32_t), 1, f) != 1) {
return 1;
}
// Write the raw point data.
if ((int)fwrite(data, k*sizeof(int), n, f) != n) {
return 1;
}
return 0;
}