/* Filename: RANSTRS.C */ // Writes an array of ten structures to a disk // file and then rereads that file randomly. #include #include #include struct cafeSt { char name[15]; float avPrice; int seats; }; void prStruct(struct cafeSt prVar); void pKey(void); FILE * fPtr; main() { int ctr; // Keep the data alphabetical and sequential to // help verify that the data is read properly. struct cafeSt cafes[10] = {{"Adam's Mark", 12.95, 135}, {"Berryhill", 20.15, 78}, {"Capricorn's", 18.40, 101}, {"Daybreak", 3.69, 63}, {"Even Steven", 13.90, 45}, {"Fike's Foods", 48.51, 73}, {"Great Gobs", 8.97, 28}, {"Ham Heaven", 5.49, 65}, {"Ike's Chili", 3.65, 40}, {"Jan's Drinks", 1.75, 25}}; struct cafeSt cafesNew[10]; // A second uninitialized array struct cafeSt aVar; // A single structure variable puts("Getting ready to write the data..."); // Didn't open the file until ready to write fPtr = fopen("cafe.dat", "w+"); // A single function call writes all the data fwrite(cafes, sizeof(cafes), 1, fPtr); puts("Just wrote the data"); fclose(fPtr); // Open the file again to show that the fwrite() worked fPtr = fopen("cafe.dat", "r+"); fread(cafesNew, sizeof(cafesNew), 1, fPtr); for (ctr=0; ctr<10; ctr++) { prStruct(cafesNew[ctr]); if (ctr==4) { pKey(); } } fseek(fPtr, (4L * sizeof(aVar)), SEEK_SET); // Fifth cafe fread(&aVar, sizeof(aVar), 1, fPtr); printf("\nFifth structure:"); prStruct(aVar); fseek(fPtr, (-3L * sizeof(aVar)), SEEK_CUR); // Third cafe fread(&aVar, sizeof(aVar), 1, fPtr); printf("\nThird structure:"); prStruct(aVar); fseek(fPtr, -1L * sizeof(aVar), SEEK_END); // Last cafe fread(&aVar, sizeof(aVar), 1, fPtr); printf("\nLast structure:"); prStruct(aVar); fclose(fPtr); pKey(); return 0; } //********************************************************** void prStruct(struct cafeSt prVar) { printf("\nName: %s\n", prVar.name); printf("Average menu price: %.2f\n", prVar.avPrice); printf("Seating: %d\n", prVar.seats); return; } //********************************************************** void pKey(void) { // Gives the user a chance to pause char pause; printf("\nPress any char then the Enter key to continue..."); cin >> pause; return; }