If I were you, I would do make a little set of functions to deal with your data structure. It will clean up the code A LOT! I think you will be able to see logic errors much easier. Here are some examples :
int ReadRecord( details * pd, FILE * pf )
{
char a[512] = { 0 };
int i = 0;
while( ( i < 4 ) && fgets( a, sizeof a, pf ) )
{
if( ( a[0] == '\r' ) || ( a[0] == '\n' ) )
continue; switch( i )
{
case 0 :
strcpy( pd->title, a );
break;
case 1 :
strcpy( pd->platform, a );
break;
case 2 :
strcpy( pd->score, a );
break;
case 3 :
strcpy( pd->release_year, a );
break;
}
++i;
}
return i;
}
void CopyRecord( details *pddest, details *pdsource )
{
strcpy( pddest->title, pdsource->title );
strcpy( pddest->platform, pdsource->platform );
strcpy( pddest->score, pdsource->score );
strcpy( pddest->release_year, pdsource->release_year );
}
void SwapRecords( details *pda, details *pdb )
{
details temp = { 0 };
CopyRecord( temp, pda );
CopyRecord( pda, pdb );
CopyRecord( pdb, temp );
}
int main()
{
int j = 0;
FILE * newFile = fopen( "ign_new.txt", "w" );
FILE * myfile = fopen( "ign.txt", "r" );
if( myfile == NULL )
{
perror (" empty file ");
return -1;
}
while( ReadRecord( &records[j], myfile ) )
{
++j;
}
fclose( myfile );
myfile = NULL;
printf( "read %d records\n", j );
int flag;
int n = j;
for( i = 1; i < n; i++ )
{
flag = 0;
for( j = 0; j < n - i; j++ )
{
if( atoi( record[j].score ) < atoi( record[j+1].score ) )
{
SwapRecords( &record[j], &record[j+1] );
flag = 1;
}
}
if( flag == 0 )
break;
}
fclose( newFile );
return 0;
}
I would advise making a WriteRecord function that works in reverse of the ReadRecord so that they can handle each other's input/output. Remember to write the blank line in WriteRecord. ;)
By the way - I haven't evaluated your logic. I have left that up to you. My point was to make functions for sequences of logic that deal with the data structure. This can simplify the processing logic and then you can see its inner workings much more clearly.
One hint - I think the terms of the for loops used in the sorting are wrong.
What the heck. Here's how I would do the sort. Often when sorting is involved a compare function is implemented for the data being compared. Here's one for this data structure :
int CompareRecords( details *pda, details * pdb )
{
return atoi( pda->score ) < atoi( pdb->score );
}
Now you can write a sort function like this :
void SortRecords( details * pd, int count )
{
int i, j;
for( j = 0; j < count - 1; ++j )
{
for( i = j + 1; i < count; ++i )
{
if( CompareRecords( &pd[j], &pd[i] ) )
SwapRecords( &pd[j], &pd[i] );
}
}
}
Note - I haven't tried this code at all. You can either try it and debug it or use what you want from it.