I was wondering what is the correct way to read in data "one-part-per-line" as compared with "one-record-per-line" formats into the same structure in C?
format1.dat:
Zacker 244.00 244.00 542.00
Lee 265.00 265.00 456.00
Walter 235.00 235.00 212.00
Zena 323.00 215.45 332.50
format2.dat:
Zacker
244.00
244.00
542.00
Lee
265.00
265.00
456.00
Walter
235.00
235.00
212.00
Zena
323.00
215.45
332.50
Mira
285.00
285.00
415.00
Using the same structure as:
typedef struct info
{
char name[20];
double test;
double quiz;
double English;
} Info;
To process data in format1.dat, I have:
int main ()
{
int n = 0;
Info record[N];
FILE *INFILE = fopen ("format1.dat", "r");
while (fscanf (INFILE, "%s %lf %lf %lf",
record[n].name, &record[n].test,
&record[n].quiz, &record[n].English) == 4)
{
printf ("%s\t%.2lf\t%.2lf\t%.2lf\n",
record[n].name, record[n].test,
record[n].quiz, record[n].English);
++n;
}
fclose (INFILE);
return 0;
}
How to read the data in format2.dat into the same struct, especially the while () block:
while ( ... ) {
printf ("%s\t%.2lf\t%.2lf\t%.2lf\n",
record[n].name, record[n].test,
record[n].quiz, record[n].English);
++n;
}
I was comparing these situation with awk which by default processes the file by row, or set the RS/FS separator if fields are in different rows.
Thanks a lot!