Search code examples
visual-c++fstreambinaryfiles

Trouble trying to read a short int from a binary file (C++)


I have a binary file where the first line contains meta data (e.g. rows 343 columns 770 ...) that I store into variables. After this, the rest of the file contains short ints correlating to various heights that I also want to store (in this bit of code I'm just testing to see if I can get a single value). My code:

  int map[800][800];
  string a;
  int numrows, numcolumns, bytespp, secondspp, lls, tls, min, max, special;
  ifstream infile;
  infile.open("usaW70N25D5.dat", ios::binary | ios::in);
  infile >>a >> numrows >> a>>numcolumns >> a>> bytespp >>a >> secondspp >>a >> lls >> a>> tls >> a>> min >>a >> max >>a >> special;
  int row = 0; max = 0;
  cout << numrows << " " << numcolumns << " " << bytespp << " " << secondspp << " " << lls << " " << tls << " " << min << " " << max << " " << special << endl;

  short int val = 0;
  infile.read((char*)&val,sizeof(infile)); 
  cout << val<< endl;

The error I get is:

Unhandled exception at 0x52ec6e9f (msvcp100d.dll) in mapproject.exe: 0xC0000005: Access violation reading location 0xfe0cfe0c.

Where am I going wrong in trying to read the file? I thought maybe that I would have to move the position one over and tried:

  int spot = infile.tellg(); spot+=1;
  infile.seekg(spot);

but that didn't help.


Solution

  • The stream reading >> doesn't read two binary bytes. It reads a string of characters.