/
mmm_io.cc
53 lines (39 loc) · 1.11 KB
/
mmm_io.cc
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
#include "mmm_io.h"
#include <cstdio>
#include <cstdlib>
#include <cassert>
using namespace mallie;
bool SaveMMM(const char *filename, double *data, int width, int height) {
FILE *fp = fopen(filename, "wb");
if (!fp) {
fprintf(stderr, "[MMM] Failed to write file: %s\n", filename);
return false;
}
int n;
n = fwrite(&width, sizeof(int), 1, fp);
assert(n == 1);
n = fwrite(&height, sizeof(int), 1, fp);
assert(n == 1);
n = fwrite(data, sizeof(double), width * height, fp);
assert(n == width * height);
fclose(fp);
return true;
}
bool LoadMMM(double **data, int &width, int &height, const char *filename) {
FILE *fp = fopen(filename, "rb");
if (!fp) {
fprintf(stderr, "[MMM] Failed to read file: %s\n", filename);
return false;
}
int n;
n = fread(&width, sizeof(int), 1, fp);
assert(n == 1);
n = fread(&height, sizeof(int), 1, fp);
assert(n == 1);
(*data) = reinterpret_cast<double *>(
malloc(sizeof(double) * (size_t)width * (size_t)height));
n = fread((*data), sizeof(double), width * height, fp);
assert(n == width * height);
fclose(fp);
return true;
}