#include #include using namespace std; typedef unsigned char byte; typedef signed char sbyte; struct observation { short int year; byte month, day; short int mint, avgt, maxt; sbyte snow, rain; byte wind; }; const int szob = sizeof(observation); int main() { if (szob != 14) { cerr << "Look out! sizeof(observation) is " << szob << ", not 14\n"; exit(1); } cout << "OK so far\n"; fstream bf("data.dat", ios::in | ios::binary); if (bf.fail()) { cerr << "Can't read data.dat\n"; exit(1); } bf.seekg(0, ios::end); int filelen = bf.tellg(); cout << filelen << " bytes = " << filelen/szob << " records\n"; if (filelen % szob != 0) { cout << filelen % szob << " bytes left over\n"; exit(1); } int wanty = 2003, wantm = 10, wantd = 30; int first = 0, last = filelen / szob - 1; while (first <= last) { int mid = (first + last) / 2; observation ob; bf.seekg(mid * szob, ios::beg); bf.read((char *) & ob, szob); cout << "looking at " << ob.year << " " << (int)ob.month << " " << (int)ob.day << "\n"; char side; if (ob.year < wanty) side = '<'; else if (ob.year > wanty) side = '>'; else if (ob.month < wantm) side = '<'; else if (ob.month > wantm) side = '>'; else if (ob.day < wantd) side = '<'; else if (ob.day > wantd) side = '>'; else side = '='; if (side == '<') first = mid + 1; else if (side == '>') last = mid - 1; else { cout << "found what I wanted\n"; break; } } bf.close(); }