-
Reading from a file
'lo everybody,
Is this the correct way to read data from a file?
Code:
while( fscanf(input, "%c, %s, %s, %d, %c, %s, %c, %6s, %s, %s, %d, %d",
&i_r.rectype,
&i_r.cust_code,
&i_r.part_no,
&i_r.ir_quantity,
&del.rectype,
&del.cust_code,
&create.rectype,
&create.cust_code,
&create.cust_name,
&create.cust_address,
&create.cust_bal,
&create.credit_limit) !=EOF)
I'm attempting to read all data from the file, and then to validate it. Any help offered is much appreciated.
Thanks
-
> Is this the correct way to read data from a file?
Whilst it might work if your data is well formatted, it does have some problems.
You should really compare the result of fscanf with the number of conversions you expect, not EOF
If fscanf returns say 5, then that leaves 7 values unassigned, and no way to tell that that is what happened. Even if you knew the result, it doesn't really help with error recovery.
In addition, %c will almost certainly read the \n character from the previous line.
Personally, I separate reading from the file and data validation
Code:
char buff[BUFSIZ];
while ( fgets( buff, BUFSIZ, input ) != NULL ) {
// now validate buff and assign to fields
// say using sscanf
}