This is my first venture into file streams
I've looked over the source-code carefully and couldn't find any differences from the book. Maybe it has something to do with my system?
Here is the console output of my program
Code:
-1208617819 DZ۱汩6 -0.05
-1079416719┌┌└F└V└└└└F└V└└└ -0.05
-1079415338└└┼+┼>┼U┼]┼⎺┼┼>┼U┼]┼⎺┼┼ -0.05
-1079415137┼=⎺]⎺┘⎺┬⎺⎺⎺⎺⎺┬⎺⎺⎺⎺⎺ -0.05
100 0.00
1000 598008216632976371697735644702348584536405246902083247220875921706093794716375762404103004004990504111786204800430166155026589905240121409306972824498630058082565445957748647537262486126146850127872.00
3553334 0.00
␊┤␊┼␊@␊┤␊┼␊-┌▒⎻├⎺⎻:/␌␋┌␊⎽$
That last line is actually my console. All alphabetic lower-case characters are screwed up afterwards.
Here is what is used to write to the file
Code:
#include <stdio.h>
struct clientData {
int acctNum;
char lastName[ 15 ];
char firstName[ 10 ];
double balance;
};
int main()
{
FILE *cfPtr;
struct clientData client = { 0, "", "", 0.0 };
if ( ( cfPtr = fopen( "credit.dat", "r+" ) ) == NULL )
printf( "File could not be opened.\n" );
else {
printf( "Enter account number "
" ( 1 to 100, 0 to end input )\n? " );
scanf( "%d", &client.acctNum );
while ( client.acctNum != 0 ) {
printf( "Enter lastname, firstname, balance\n? " );
fscanf( stdin, "%s%s%lf", client.lastName, client.firstName, &client.balance );
fseek( cfPtr, ( client.acctNum - 1 ) * sizeof( struct clientData ), SEEK_SET );
fwrite( &client, sizeof( struct clientData ), 1, cfPtr );
printf( "Enter account number\n? " );
scanf( "%d", &client.acctNum );
}
fclose( cfPtr );
}
return 0;
}
Here is the example to read from the file, the 1st block I posted is this programs output.
Code:
#include <stdio.h>
struct clientData {
int acctNum;
char lastName[ 15 ];
char firstName[ 10 ];
double balance;
};
int main()
{
FILE *cfPtr;
struct clientData client = { 0, "", "", 0.0 };
if ( ( cfPtr = fopen( "credit.dat", "r" ) ) == NULL )
printf( "File could not be opened.\n" );
else {
printf( "%-6s%-16s%-11s%10s\n", "Acct", "Last Name", "First Name", "Balance" );
while ( !feof( cfPtr ) ) {
fread( &client, sizeof( struct clientData ), 1, cfPtr );
if ( client.acctNum != 0 )
printf( "%-6d%-16s%-11s%10.2f\n",
client.acctNum, client.lastName,
client.firstName, client.balance );
}
fclose( cfPtr );
}
return 0;
}