Monday, April 23, 2007

Read and print a serial file using C

If you have a serial .dat file that has data like these below, you can easily import and use them with C (for C++ it is almost the same).
Sample file:
If the file is named customers.dat, use the code below to read and print the data with C.
#include <stdio.h>
int main()
{
int number;
char name[30];
double bill;
FILE *cfPt; /*File pointer .dat */
if ((cfPtr=fopen("customers.dat", "r"))==NULL)
printf("File could not be opened\n");
else {
printf("%-10s%-13s%s\n", "Number", "Name", "Bill");
fscanf(cfPtr, "%d%s%lf", &number, name, &amp;amp;amp;amp;bill);
while (!feof(cfPtr)) {
printf("%-10d%-13s%7.2f\n", number, name, bill);
fscanf(cfPtr, "%d%s%lf", &number, name, &amp;amp;amp;amp;bill);
}
fclose(cfPtr);
}
return 0;
}

No comments: