#include #include #include typedef struct Student { char *name; int age; double gpa; } Student; void printStudent( FILE *fp, const Student *s ) { int val = fprintf( fp, "Name=%20s, age=%3d, gpa=%4.2lf\n", s->name, s->age, s->gpa ); printf( "Return code = %d\n" , val ); } void readStudent( FILE *fp, Student *s ) { static char buffer[ 1024 ]; fscanf( fp, "%1023s %d %lf", buffer, &s->age, &s->gpa ); s->name = strdup( buffer ); } void cleanup( Student *s ) { free( s->name ); } int main( ) { Student s1; Student s2 = { strdup( "Pat" ), 26, 3.6 }; Student s3; Student s4; FILE *fout; FILE *fin; printf( "Sizeof struct is %d\n", sizeof( s1 ) ); s1.age = 40; s1.gpa = 4.0; s1.name = strdup( "Chris" ); fout = fopen( "output.txt", "w" ); printStudent( fout, &s1 ); printStudent( fout, &s2 ); fin = fopen( "input.txt", "r" ); if( fin == NULL || fout == NULL ) { fprintf( stderr, "Error opening files\n" ); return 1; } printf( "Reading student: " ); readStudent( fin, &s3 ); printf( "Reading student: " ); readStudent( fin, &s4 ); printStudent( fout, &s3 ); printStudent( fout, &s4 ); cleanup( &s1 ); cleanup( &s2 ); cleanup( &s3 ); cleanup( &s4 ); fclose( fin ); fclose( fout ); return 0; }