Saturday, June 18, 2011

Reading binary files from cin (C++/windows/VS)

As a TA assignment I needed to read binary files straight from cin using C++ on windows. Although at first this seems like an extremely easy task, it is a bit more complex than what I expected. Anyhow, eventually I got it to work. This code sample counts the number of characters in each line. Arguably, the concept of a “line” is thin, so it’s either 100 bytes or eof(). Makes sense? :)

#include "stdafx.h"
#include
#include
#include
#include  //_O_BINARY
#include  //_setmode
using namespace std;
int _tmain(int argc, _TCHAR* argv[]) {
 char temp[100];
 int readBufSize;
 int max = -1;
 int min = 1000;
 int total_number_bytes = 0;
 bool done = false;
 // see: http://tinyurl.com/clzq6m
 if (_setmode(_fileno(stdin), _O_BINARY) == -1)
  cout << "ERROR: cin to binary:" << strerror(errno);
 while (!done)
 {
  cin.read(temp, sizeof(temp));
  readBufSize = cin.gcount();
/*
  for (int i=0; i {
  cout.setf(ios::hex, ios::basefield);
  cout << (int) temp[i] << endl;
  cout.setf(ios::dec, ios::basefield);
  }
*/
  max = (readBufSize > max)?readBufSize:max;
  min = (readBufSize < min)?readBufSize:min;
  total_number_bytes += readBufSize;
  if(cin.fail() || cin.bad() || cin.eof()) {
  if (cin.eof()) done = true;
  cin.clear();
  }
 }
 cout << "MAX: " << max <<
                " MIN: " << min <<
  " TOTAL: " << total_number_bytes;
 return 0;
}
To run it it would do something like: prog.exe < file.jpg. Any suggestions or comments? Drop me a line.

2 comments: