I've been searching all over the web, implementing the information as shown, but for reasons I don't understand, I can't get this very simple code to work. It's supposed to be a simple sanity check. I'm using FILE* for speed (speed being the priority here). First, the variables...
#include <iostream>
#include <fstream>
#include <vector>
#include <cmath>
using namespace std;
int main()
{
//Declaration
int g = 1, dim_hi = 5, pop = 6;//variables I'll use to write to binary file
char OA = 'D';//variable I'll use to write to binary file
const short d_size = sizeof(double);
const short c_size = sizeof(char);
const short i_size = sizeof(int);
FILE * outFile;
int read_g = 0, read_dim = 0, read_pop = 0;//variables I'll use to READ from file
char read_oa ='a';//variable I'll use to READ from file
Next I write to the file. As far as I can tell (based on the size of the output file) this section of code is working properly. My intent is to write three integers and a char to the file, one after another...
//Binary File Output
outFile = fopen ("myfile.bin", "ab");
fwrite (&dim_hi , i_size, i_size, outFile);
fwrite (&pop , i_size, i_size, outFile);
fwrite (&g , i_size, i_size, outFile);
fwrite (&OA , c_size, c_size, outFile);
fclose (outFile);
According to the internet, I should have a file that, in binary, contains the values: 561D. However, according to the following code...
//Binary File Input
outFile = fopen ("myfile.bin", "rb");
fread ((void*)&read_dim , i_size, 1, outFile);
fread ((void*)&read_pop , i_size, 1, outFile);
fread ((void*)&read_g , i_size, 1, outFile);
fread (&read_oa , c_size, 1, outFile);
fclose (outFile);
return 0;
}
Note I've also tried (char*)&read_dim, and simply &read_dim. What I get is:
read_dim = 5
read_pop = -858993460
read_g = -858993460
read_oa = 9 "
I don't get it. It's a list of writes and a list of reads. Same system, etc. Why don't the writes correspond to the reads? I've read something about padding, but none of the examples use seekg (or an equivalent command for FILE*) objects to move around in the file.
Does anything know what's wrong with this code?
Once I sort out the issues with this simple test, I want to do something similar with rows of a matrix (this matrix can eventually contain tens of thousands of elements)...
vector<vector<double> > depop(pop, vector<double> (dim_hi,0));
short v_size = dim_hi*d_size;
for(int i = 0; i < pop; i++)
{
fwrite (&depop[i] , d_size, v_size, outFile);
}
// followed by the read command...
Thank you all in advance!
Links I've read:
- http://www.cplusplus.com/reference/cstdio/fread/
- http://www.cplusplus.com/forum/unices/9187/
- https://stackoverflow.com/questions/8329767/writing-into-binary-files#=
- Error by reading binary file with c++
- How to read a float from binary file in C?
- Reading in a File's Binary
- Writing a binary file in C++ very fast
- Reading and writing C++ vector to a file
- Problem writing int to binary file in C