Reputation: 109
Until now I save a file with a "csv" format in C. However, the size of files are large, so execution time in I/O step is very long for me. Thus, I tried to save a binary file in C, but, some garbage data are inserted when reading a file in Python.
The types of data in file are same for below:
int double int double double ...
I tried in C
...
FILE* fp_result = fopen([filepath]); // the file format is .bin
double w[60];
double th[60];
...
int n = 0;
double K = 10.0;
int num = 30;
fwrite(&n, sizeof(int), 1, fp_result);
fwrite(&K, sizeof(double), 1, fp_result);
fwrite(&num, sizeof(int), 1, fp_result);
fwrite(w, sizeof(double), 60, fp_result);
fwrite(th, sizeof(double), 60, fp_result);
fclose(fp_result);
And then I tried in Python
import numpy as np
x = np.fromfile([filepath])
print(x)
the result is
array[0, 1e-365, ..., 10e0, ...]
how can I solve this problem?
Upvotes: 1
Views: 79
Reputation: 213879
This code:
fwrite(n, sizeof(int), 1, fp_result);
fwrite(K, sizeof(double), 1, fp_result);
fwrite(num, sizeof(int), 1, fp_result);
will promptly crash. You want:
fwrite(&n, sizeof(int), 1, fp_result);
fwrite(&K, sizeof(double), 1, fp_result);
fwrite(&num, sizeof(int), 1, fp_result);
You'll also want to enable maximum compiler warnings (-Wall -Wextra
if using GCC), so the compiler tells you about the bug above.
After fixing that, all you'll have to do is thread the binary data in Python. See this answer.
Upvotes: 1