Recently I was reading file processing section of C How to Program, 7th ed by Deitel. For writing to a file, it uses this example:
// Fig. 11.2: fig11_02.c
// Creating a sequential file
#include <stdio.h>
int main( void )
{
unsigned int account; // account number
char name[ 30 ]; // account name
double balance; // account balance
FILE *cfPtr; // cfPtr = clients.dat file pointer
// fopen opens file. Exit program if unable to create file
if ( ( cfPtr = fopen( "clients.dat", "w" ) ) == NULL ) {
puts( "File could not be opened" );
} // end if
else {
puts( "Enter the account, name, and balance." );
puts( "Enter EOF to end input." );
printf( "%s", "? " );
scanf( "%d%29s%lf", &account, name, &balance );
// write account, name and balance into file with fprintf
while ( !feof( stdin ) ) {
fprintf( cfPtr, "%d %s %.2f\n", account, name, balance );
printf( "%s", "? " );
scanf( "%d%29s%lf", &account, name, &balance );
} // end while
fclose( cfPtr ); // fclose closes file
} // end else
} // end main
as you can see, it scans and prints data first in else block, then in a while loop. since I thought it's pointless to do it twice, it just removed the if-else part and compiled it. well it worked fine but then I realized it duplicates the last line of input in the output file. in the Deitel version it does not.
what's wrong with my version?? why does it duplicates the last line? I think this might be an issue with loop condition but I'm not sure..
edit: this code is used by Dietel and I don't believe it's wrong because he is using if-else to fix the problem caused by !feof. but i wanted to know how do i fix it without that if-else.
in edited version without if-else and only with loop the input and output are:
input:
1 test 25.6
2 some 95
output:
1 test 25.6
2 some 95
2 some 95