How to read numbers from a file in C ++?

My main question is how do you read data from a file that is not of type char . I am writing a data file from MATLAB as follows:

x=rand(1,60000); fID=fopen('Data.txt','w'); fwrite(fID,x,'float'); fclose(fID); 

Then, when I try to read it in C ++ using the following code, "num" does not change.

 #include <iostream> #include <fstream> using namespace std; int main() { fstream fin("Data.txt",ios::in | ios::binary); if (!fin) { cout<<"\n Couldn't find file \n"; return 0; } float num=123; float loopSize=100e3; for(int i=0; i<loopSize; i++) { if(fin.eof()) break; fin >> num; cout<< num; } fin.close(); return 0; } 

I can read and write the file in matlab in order, and I can read and write in C ++, but I can not write in matlab and read in C ++. The files I write in matlab are in the format I want, but the files in C ++ seem to write / read numbers in the text. How do you read a series of float from a file in C ++ or what am I doing wrong?

edit: The loop code is dirty because I did not want an infinite loop, and the eof flag was never set.

+4
source share
3 answers

Formatted I / O using << and >> really reads and writes numeric values ​​as text.

Matlab presumably writes floating point values ​​in binary format. If it uses the same format as C ++ (most implementations of which use the standard binary IEEE format), then you can read the bytes using unformatted input and reinterpret them as a floating point value according to the lines:

 float f; // Might need to be "double", depending on format fin.read(reinterpret_cast<char*>(&f), sizeof f); 

If Matlab does not use a compatible format, you need to find out which format it uses and write code to convert it.

+6
source

You need to read and write the same format. In this regard, what you wrote from Matlab is an unformatted sequence of bytes that may or may not be read depending on whether you use the same system. You can probably read this unformatted byte sequence in a C ++ program (for example, using std::istream::read() ), but you should not consider the data you need to save.

To actually store data, you need to know the data format. The format can be binary or text, but you must clearly understand what the bytes mean, in what order they appear, how many there are or how to determine the end, if the value, etc.

+3
source

Using fwrite is not a good idea, because it will output data in an internal format that may or may not be easily read in your program.

Matlab has other ways of writing output, for example. functions like fprintf. It’s better to write your data in this way, then it should be obvious how to read it back to another application.

Just use fprintf(fID, "%f\n", x) and then you can use scanf to read this in C / C ++.

+1
source

All Articles