Hello all,
I am working on a project and I am having some difficulties sorting. I am trying to read in from a binary file and sort the structure but I am not sure I have it setup correctly. Any advice would be appreciated.
Code:
/* HorseData structure definition */
struct horseData {
int number;
char name [ 25 ];
int dob;
int height;
char father [ 25 ];
char mother [ 25 ];
}; /* End structure horseData */
Code:
/* Function Prototype */
int newLine();
void createData();
int mainMenu();
void addHorse();
void addRace();
void viewHorse();
void sortData();
void sortHorse();
Code:
/* Function sortHorse definition */
void sortHorse()
{
int counter;
int counter2;
int hold;
int pass;
int record;
int swap;
/* Horses.dat file pointer */
FILE *shPtr;
/* Load horseData with default information */
struct horseData sortHorse = { 0, "", 0, 0, "", "" };
/* Fopen opens file; exits program if file cannot be opened */
if ( ( shPtr = fopen( "horses.dat", "rb" ) ) == NULL ) {
printf( "File could not be opened\n" );
} /* End if */
/* Read records from file */
else {
/* While not end of file */
while( !feof( shPtr ) ) {
fscanf( shPtr, "%s", sortHorse.name );
printf( "%s", sortHorse.name );
record++;
} /* End while */
/* Fclose closes the file */
fclose( shPtr );
/* Begin sorting the array */
for ( pass = 1; pass <= record; pass++ ) {
swap = 0;
/* Traverse and compare unsorted part of array */
for ( counter = 0; counter < record - 1; counter++ ) {
/* Compare adjacent array elements */
if ( sortHorse.name [ counter ] > sortHorse.name [ counter + 1 ] ){
swap = 1;
hold = sortHorse.name [ counter ];
sortHorse.name [ counter ] = sortHorse.name [ counter + 1 ];;
sortHorse.name [ counter + 1 ] = hold;
} /* End if */
} /* End for */
/* Break loop if array is already sorted */
if ( !swap ) {
break;
} /* End if */
} /* End for */
} /* End else */
printf( "New sorted data - \n" );
/* Fopen opens file; exits program if file cannot be opened */
if ( ( shPtr = fopen( "sorted.txt", "w" ) ) == NULL ) {
printf( "File could not be opened\n" );
} /* End if */
else {
/* Output sort array */
for( counter2 = 0; counter2 < record; counter2++ ) {
fprintf ( shPtr, "%s\n", sortHorse.name [ counter2 ] );
printf( " %s ", sortHorse.name [ counter2 ] );
} /* End for */
/* Fclose closes the file */
fclose( shPtr );
} /* End else */
} /* End sortHorse function */
Thanks
DMKanz07