In the main body
fscanf( tfPtr, "%d %f", &accountNum, &balance );
is causing a SEGMENTATION FAULT. What is really throwing me off is the fact that I use the same fscanf function in getTransaction() with no problems at all. Any ideas on what might be wrong?
Code:
#include <stdio.h>
int match( int account, FILE *fPtr );
float getTransaction( int account, FILE *transaction );
int main()
{
FILE *ofPtr;
FILE *tfPtr;
FILE *nfPtr;
int accountNum;
char *name;
float balance;
ofPtr = fopen( "oldmast.dat", "r" );
tfPtr = fopen( "trans.dat", "r" );
nfPtr = fopen( "newmast.dat", "w" );
/* INCORRECT USE OF feof() it runs last member twice */
while ( !feof( ofPtr ) ) {
fscanf( ofPtr, "%d %s %f", &accountNum, name, &balance );
printf( "%d\n", accountNum );
balance += getTransaction( accountNum, tfPtr );
printf( "%d %s %.2f\n", accountNum, name, balance );
fprintf( nfPtr, "%d %s %.2f\n", accountNum, name, balance );
}
rewind( tfPtr );
rewind( ofPtr );
while ( !feof( tfPtr ) ) {
/* This fscanf is causing a segmentation error
-----------------------------------------------------------*/
fscanf( tfPtr, "%d %f", &accountNum, &balance );
/*
if ( !match( accountNum, ofPtr ) ) {
printf( "There is no match for this account in the oldmaster file\n" );
}
*/
}
/* This is a test of the match function */
printf( "%d\n", match( 1, ofPtr ) );
/* CLOSING ANY FILE IS CAUSING A SEGMENTATION FAULT */
// fclose( ofPtr );
// fclose( tfPtr );
// fclose( nfPtr );
return 0;
}
float getTransaction( int account, FILE *fPtr )
{
int accountNum = 0;
float dollarAmount = 0;
rewind( fPtr );
while( !feof( fPtr ) ) {
fscanf( fPtr, "%d %f", &accountNum, &dollarAmount );
if ( accountNum == account ) {
rewind( fPtr );
return dollarAmount;
}
}
rewind( fPtr );
return 0.0;
}
/* ONLY WORKS WITH ofPtr */
int match( int account, FILE *fPtr )
{
int accountNum = 0;
// float dollarAmount = 0.0;
float balance;
char *name;
rewind( fPtr );
while ( !feof( fPtr ) ) {
fscanf( fPtr, "%d %s %f", &accountNum, name, &balance );
if ( account == accountNum ) {
rewind( fPtr );
return 1;
}
}
rewind( fPtr );
return 0;
}