#include #include #include #include #include using namespace std; /* f.open(string name); f.open(string name, ios::in | ios::out | ios::binary | ios::trunc | ios::app | ios::ate); f.write(char * pointer, int numbytes); f.read(char * pointer, int numbytes); int bytesread = f.gcount(); int f.tellg(); // reading position int f.tellp(); // writing position f.seekg(int relative_position, ios::beg or ios::end or ios::cur); f.seekp(int relative_position, ios::beg or ios::end or ios::cur); */ int main(int argc, char * argv[]) { char wanted[60]; strcpy(wanted, argv[1]); int len = strlen(wanted); for (int i = len; i < 48; i += 1) wanted[i] = ' '; wanted[48] = '\0'; cout << "search for \'" << wanted << "\'\n"; const string fname = "/home/www/class/een318/named-places.txt"; ifstream fi(fname); if (fi.fail()) { cerr << "Can't read \"" << fname << "\"\n"; exit(1); } fi.seekg(0, ios::end); int filesize = fi.tellg(); fi.seekg(0, ios::beg); char line[120]; int nrec = filesize / 115; // [115] is the position of the '\n' character int first = 0, last = nrec - 1; while (first <= last) { int mid = (first + last) / 2; fi.seekg(mid * 115, ios::beg); fi.read(line, 115); line[115] = '\0'; cout << "seeing " << mid << ": '" << line << "'\n"; char c = line[58]; line[58] = '\0'; // line is now a C string that stops at position 58, where population begins int r = strcmp(line + 10, wanted); // line + 10 skips the numeric code and state abbreviation if (r == 0) { line[58] = c; // set line back to be the whole record not ending until [115] cout << "record " << mid << ": '" << line << "'\n"; break; } if (r > 0) last = mid - 1; else first = mid + 1; } fi.close(); }