问题
I am trying to read numerical data from a binary file containing 100 double values and store it in an array called myArray. When I print myArray nothing is being shown, as if myArray has never been filled. Any help is appreciated.
int main()
{
int file_len;
ifstream infile;
infile.open("mybinfile.bin", ios::binary | ios::in);
if (!infile.is_open())
{
cout << "Error in opening the file. " << endl;
}
else
{
const int file_len = 100;
std::vector<char> myVect;
myVect.resize(file_len);
int i = 0;
infile.read((char *) (&temp), sizeof(char));
myVect[i] = temp;
while(!infile.eof())
{
myVect[i] = temp;
i++;
infile.read((char *) (&temp), sizeof(char));
}
for (int i = 0; i < 100 ; i++)
{cout << i << ": " << myVect[i]<< endl;}
}
infile.close();
return 0;
}
回答1:
Here
infile.read((char*)&myArray, file_len * sizeof(double));
You pass the pointer to the pointer to double. It should be
infile.read((char*)myArray, file_len * sizeof(double));
Makes me wonder why you didn't see a crash, since writing into random memory almost never turns out well.
回答2:
Here is one example of brute-force serialization and de-serialization. Note that serialization in general is tricky, due to e.g. endianness, different floating-point formats, conversion between decimal text representations and binary and whatnot.
#include <fstream>
using std::string;
using std::ofstream;
using std::ifstream;
using std::cout;
string fname("/tmp/doubles.bin");
void write_doubles()
{
ofstream of;
of.open(fname.c_str(), std::ios::binary | std::ios::out);
double arr[100];
for (int i = 0; i < 100; i++)
{
arr[i] = static_cast<double>(i+100);
}
of.write((char*)arr, 100*sizeof(double));
}
void read_doubles()
{
ifstream ifs;
ifs.open(fname.c_str(), std::ios::binary | std::ios::in);
double arr[100];
ifs.read((char*)arr, 100*sizeof(double));
for (int i = 0; i < 100; i++)
{
cout << "Arr[i]: " << arr[i] << ", ";
}
cout << '\n';
}
int main()
{
write_doubles();
read_doubles();
return 0;
}
来源:https://stackoverflow.com/questions/26735428/storing-numerical-value-from-a-binary-file-into-an-array-c