Hi guys
I have been studying C on my own and want to access the contents of a file for the purpose of sorting them. I'm using 'bubble sort' because it seems a simple way to do content sorting. Anyway, my code compiles and runs but fails to print on screen the file content. Here is my code:
Code:
/* read, sort and display customer's id and balances */
#include <stdio.h>
#include <stdlib.h>
#define MAX_CUSTOMERS 100
struct custRec
{
int ID;
float Bal;
};
/* prototypes of functions */
int readInput(struct custRec *);
void sortData(struct custRec *, int);
void printRecords(struct custRec*, int);
int main()
{
int noOfRecords;
struct custRec custs[MAX_CUSTOMERS];
/* read the input */
noOfRecords = readInput(custs);
/* print the initial values */
printf("Before sorting\n");
printRecords(custs,noOfRecords);
/* sort the array */
sortData(custs,noOfRecords);
/* print the sorted values */
printf("Ater sorting\n");
printRecords(custs,noOfRecords);
system("pause");
return 0;
}
/* read the input file and put data into the
array that records points at */
int readInput(struct custRec *records)
{
FILE *input = fopen("cust.dat","r");
int noOfRecords = 0;
char tempLane[240];
int tempCustId;
float tempCustBal;
if ( input == 0) /* can't open cust.dat */
{
fprintf(stderr,"Can not open cust.dat\n");
fprintf(stderr,"please check\n\n");
exit(-1);
}
while (fgets(tempLane,240,input))
{
/* if the first character is a "#" ignore */
if (tempLane[0] == '#')
{
continue;
}
/* make sure that the line has 2 numbers */
if (sscanf(tempLane,"%d, %f",
&tempCustId, &tempCustBal) == 2)
{
records[noOfRecords].ID = tempCustId;
records[noOfRecords].Bal = tempCustBal;
noOfRecords++;
}
}
fclose(input);
return noOfRecords;
}
/* sort the records */
void sortData(struct custRec *custs, int noOfRecs)
{
int inner, outer, didSwap;
struct custRec temp;
/* sort the array */
for (outer = 1; outer < noOfRecs; outer++)
{
didSwap = 0;
for (inner = noOfRecs-1; inner >= outer ; inner--)
{
if (custs[inner-1].ID > custs[inner].ID )
{
temp = custs[inner-1];
custs[inner-1] = custs[inner];
custs[inner] = temp;
didSwap = 1;
}
} /* inner loop */
if (didSwap == 0)
{
break;
}
} /* outer loop */
return ;
}
void printRecords(struct custRec* custs, int noOfRecs)
{
int i;
/* print values */
printf("Cust ID Balance\n");
for (i = 0; i < noOfRecs ; i++)
{
printf("%5d %12.2f\n",
custs[i].ID, custs[i].Bal);
}
return;
}
My input file, 'cust.dat', merely contains two columns of values with a header:
Cust ID Bal
313 0.00
453 45.43
502 71.23
101 301.56
892 9.08
475 192.41
792 389.00
912 229.67
343 18.31
633 59.54
999 1.00
0 0.00
Thanks for any help.