Solution for Exercise 22-15
ex2215
#include <stdio.h> #include <stdlib.h> #include <string.h> int main() { struct agent { char actor[32]; int year; char title[32]; }; struct agent bond; FILE *jbdb; int r; jbdb = fopen("bond.db","r"); if(!jbdb) { puts("SPECTRE wins!"); exit(1); } puts("First read-through:"); while( !feof(jbdb) ) { printf("%ld:\t",ftell(jbdb)); r = fread(&bond,sizeof(struct agent),1,jbdb); if( r==0 ) break; printf("%s\t%d\t%s\n", bond.actor, bond.year, bond.title); } /* restart! */ rewind(jbdb); puts("Second read-through:"); while( !feof(jbdb) ) { printf("%ld:\t",ftell(jbdb)); r = fread(&bond,sizeof(struct agent),1,jbdb); if( r==0 ) break; printf("%s\t%d\t%s\n", bond.actor, bond.year, bond.title); } /* close and exit */ fclose(jbdb); return(0); }
Output
First read-through:
0: Sean Connery 1962 Dr. No
68: Roger Moore 1973 Live and Let Die
138: Pierce Brosnan 1995 GoldenEye
204: Second read-through:
0: Sean Connery 1962 Dr. No
68: Roger Moore 1973 Live and Let Die
138: Pierce Brosnan 1995 GoldenEye
204:
Notes
* The file pointer offsets, returned from the ftell() statements, appear in the first column of output.
* Curiously, the 204:
values in the output indicate the the ftell() statement is executed within the while loop before the EOF is encountered. (The loop keeps spinning.) This funky output indicates that it's the if test on the r
value returned from the fread() function that terminates the loop.
Copyright © 1997-2024 by QPBC.
All rights reserved