Hi i'm writing a program that reads records from a file, then sorts these records by the person's firstname, and stores the sorted data in a new file.
Heres the code:
Everything works fine, except it stores garbage at the end of the last record. If i set the array to the maximum number of records, no garbage is present. How do i fix this? How would i implement a dynamic array, or is that not needed in this case.
//Structure of the records
struct Person
{
char firstName[ 20 ];
char lastName[ 20 ];
int age;
};
void store()
{
//creates file
fstream MyFile;
fstream SortFile;
MyFile.open( FILE_PATH, ios::binary | ios::in );
SortFile.open( FILE_PATH_TWO , ios::binary | ios::in | ios::out );
Person myArray[ 100 ];
Person temp;
int i = 0;
MyFile.read(( char* ) &temp, sizeof( temp ));
//read file till the end of the record, store the records into an array for sorting
while ( !MyFile.eof())
{
if ( temp.current == true )
{
myArray[ i ] = temp;
}
MyFile.read(( char* ) &temp, sizeof( temp ));
i++;
}
bubbleSort( myArray, i ); //pass array to bubblesort function
SortFile.write(( const char* ) &myArray, sizeof( myArray )); //write the array into a file **error occurs here**
SortFile.close();
}
void bubbleSort( Person item[], int size )
{
int swaps;
Person temp;
int right;
int left;
do
{
swaps = 0;
left = 0;
right = 1;
while ( right < size )
{
if ( strcmp(item[ right ].firstName, item[ left ].firstName ) < 0 )
{
temp = item[ left ];
item[ left ] = item[ right ];
item[ right ]= temp;
swaps++;
}
left++;
right++;
}
} while ( swaps > 0 );
}
e.g.
Bill Jack 17
Jacob Mcdonald 32
Joe Bloggs 99
Zoey Clement 23
G G G G G G G G G G G G G G G G
G G G G G G G G G G G G G G G G
G G G G G G G G G G G G G G G G
G G G G G G G G G G G G G G G G
G G G G G G G G G G G G G G G G
Cheers