-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathbinaryIO.cpp
80 lines (62 loc) · 1.72 KB
/
binaryIO.cpp
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
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <string.h>
#include <fstream>
using namespace std;
int readBinaryHeader(int* dim, int* lg, string filename);
int readBinaryImage(double *Y, string filename);
void writeBinary(string filename, int dim, int* lg, double *Y);
int readBinaryHeader(int *dim, int *lg, string filename) {
FILE *file;
char filename_char[256];
strcpy(filename_char, filename.c_str());
file = fopen(filename_char , "rb");
// first byte: dimension number
fread(dim, sizeof(int), 1, file);
// 2nd~4th bytes: size in each dimension
for (int i = 0; i < *dim; i++) {
fread(&lg[i], sizeof(int), 1, file);
} // end of for
fclose(file);
return 0;
}
int readBinaryImage(double *Y, string filename) {
FILE *file;
char filename_char[256];
strcpy(filename_char, filename.c_str());
file = fopen(filename_char , "rb");
rewind(file);
int dim = 0;
int lg[3] = {1};
// first byte: dimension number
fread(&dim, sizeof(int), 1, file);
// 2nd~4th bytes: size in each dimension
int sz = 1;
for (int i = 0; i < dim; i++) {
fread(&lg[i], sizeof(int), 1, file);
sz *= lg[i];
} // end of for
// remaing bytes: data (double)
fread(Y, sizeof(double), sz, file);
fclose(file);
return 0;
}
void writeBinary(string filename, int dim, int *lg, double *Y) {
FILE *file;
char filename_char[256];
strcpy(filename_char, filename.c_str());
file = fopen(filename_char , "wb");
// first byte: dimension number
fwrite(&dim, sizeof(int), 1, file);
// 2nd~4th bytes: size in each dimension
int sz = 1;
for (int i = 0; i < dim; i++) {
sz *= lg[i];
fwrite(&lg[i], sizeof(int), 1, file);
}
// remaing bytes: data (double)
fwrite(Y, sizeof(double), sz, file);
// close file
fclose(file);
}