#include #include struct record { short int year; unsigned char month, day; float mint, avgt, maxt; float wind; short int precip; }; void print_record(struct record * r) { printf("%d-%d-%d T=(%.1f, %.1f, %.1f) P=%d W=%.1f\n", r->year, r->month, r->day, r->mint, r->avgt, r->maxt, r->precip, r->wind); } int main() { FILE * f = fopen("weather.dat", "r"); if (f == NULL) { fprintf(stderr, "Can't read weather.dat\n"); exit(1); } printf("the struct is %d bytes long\n", sizeof(struct record)); struct record r; fseek(f, 0, SEEK_END); int flen = ftell(f); printf("length of file is %d\n", flen); int nrecs = flen / sizeof(r); printf("%d records\n", nrecs); int wanty, wantm, wantd; printf("Enter wanted y m d: "); scanf("%d %d %d", & wanty, & wantm, & wantd); int minrec = 0, maxrec = nrecs-1; while (1) { int midrec = (minrec + maxrec) / 2; fseek(f, midrec * sizeof(r), SEEK_SET); fread(& r, sizeof(r), 1, f); if (r.year == wanty && r.month == wantm && r.day == wantd) { print_record(& r); break; } if (wanty < r.year || wanty == r.year && wantm < r.month || wanty == r.year && wantm == r.month && wantd < r.day) maxrec = midrec - 1; else minrec = midrec + 1; } }