Code:
/* HorseData structure definition */
struct horseData {
int number;
char name [ 25 ];
int dob;
int height;
char father [ 25 ];
char mother [ 25 ];
}; /* End structure horseData */
I am trying to write a sort that will open up horses.dat extract each of the horses names from the file and then sort them. The problem I am running into is I am not sure how to go about this. I have written the follow in attempts to accomplish this task but it does not work. I believe the core concept is right but I am not sure my syntax is correct.
Code:
/* Function sortHorse definition */
void sortHorse()
{
/* Declare variables */
char name [ 25 ][ 50 ];
int counter;
int counter1;
int counter2;
char hold [ 50 ];
int pass;
int record;
int swap;
/* Horse.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", "r" ) ) == NULL ) {
printf( "File could not be opened\n" );
} /* End if */
/* Read records from file */
else {
printf( "\n" );
printf( "Original unsorted data - \n" );
/* While not end of file */
while( !feof( shPtr ) ) {
fscanf( shPtr, "%s", name [ record ] );
printf( " %s ", name [ record ] );
record++;
} /* End while */
/* Fclose closes the file */
fclose( shPtr );
printf( "\n\n" );
/* 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 ( strcmp ( name [ counter ], name [ counter + 1 ] ) > 0 ) {
swap = 1;
strcpy ( hold, name [ counter ] );
strcpy ( name [ counter ], name [ counter + 1 ] );
strcpy ( name [ counter + 1 ], hold );
} /* End if */
} /* End for */
printf ( "After Pass %d: \n", pass );
/* Display array after each pass */
for ( counter1 = 0; counter1 <= record - 1; counter1++ ) {
printf( " %s ", &name [ counter1 ] );
} /* End for */
printf( "\n\n" );
/* 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", name [ counter2 ] );
printf( " %s ", name [ counter2 ] );
} /* End for */
/* Fclose closes the file */
fclose( shPtr );
} /* End else */
} /* End sortHorse function */
Thanks
DMKanz

