I am using iostream to collect data from a device.First I Write file in ASCII mode,it works well,but taking quite alot of time.Then I switsch to write in Binary mode and it is faster.
float dist[41616];
ofstream d_ofs( "numbers.dat",ios::out |ios::app|ios::binary);
// this is from the device API getting distance datas
res = GetDistances (hnd, dist, sizeof dist);
d_ofs.write((char*)&dist,sizeof dist);
d_ofs.close();
After the data collection,I have to convert the data inside "numbers.txt" to be readable by my tutor, in a txt file.I assume it is to change binary raw data to ASCII. so I read the file first and then write in ASCII format.
I get numbers,but unfortunately they are not the right numbers.I guess there should be special format for this convert process.But so far I have not found the solution due to my poor coding knowledge.So can anyone give me a hand? Many thanks in advance.
Here is my code:
double fnum[41616]; // here is the mistake,it should be float[]
ifstream in("numbers.dat", ios::in | ios::binary);
in.read((char *) &fnum, sizeof fnum);
MessageBox("Read File done");
ofstream fout("output.txt");
for(int k=0; k<41616; k++) // show values read from file
fout <<dec<<"\t" << fnum[k] ;
in.close();
fout.close();
Conclude:
The stupid mistake by me is in the data type.I wrote double[] instead of float[] in the second part.It is really emba开发者_开发技巧rrasing.Hopefully this post can help beginners like me.
You seem to be saving as float and reading as double. The read will (usually) be twice as large as the write so every double you read will actually be reading two of the written floats. You will get the wrong numbers because of this.
try changing the
double fnum[41616]
to
float fnum[41616]
Also, its probably for the best not to call a binary file *.txt as its a little confusing.
Its also confusing calling a double array fnum
- as the f suggests floats
精彩评论