Reputation: 4956
I am new in C++ in general, and thus, also in file handling in C++.
I need to read a .raw
file which has 16-bit integers
, and have dimension 512 x 512
.
For that I am using following code:
ifstream myData("myData.raw");
short value;
int i = 0;
char buf[sizeof(short)];
while (myData.read(buf,sizeof(buf)))
{
memcpy(&value, buf, sizeof(value));
cout << value << " ";
i++;
}
cout << endl << "Total count: " << i << endl;
The value i am getting for i
is not 512 x 512
. So I guess something is not right.
Can someone please help me in this regard?
Upvotes: 1
Views: 10471
Reputation: 4289
The default open mode is "text" and some characters will be possibly dropped or treated as end of file. ios::binary stops these alterations.
#include <iostream>
#include <fstream>
using namespace std;
int main() {
ifstream myData("myData.raw", ios::binary);
short value;
int i = 0;
char buf[sizeof(short)];
while (myData.read(buf, sizeof(buf)))
{
memcpy(&value, buf, sizeof(value));
cout << value << " ";
i++;
}
cout << endl << "Total count: " << i << endl;
}
Upvotes: 2