-
Reading from a File
We are attempting to read a file, and input data into an array of structures. The array of structures is defined in the main program as:
The structure is defined as:
Code:
typedef struct
{
char code[5];
char food_name[13];
int amount;
}fastfood;
Our function is called in the main program as:
Code:
for(i=0; i < 10; i++)
ff[i] = read_info(fptr);
where fptr is a pointer to the file.
Here is our function:
Code:
fastfood read_info (FILE *fptr)
{
fastfood ff;
char line[100];
fgets(line, 100, fptr);
ff.code[5] = char(strtok(line, " "));
ff.food_name[13] = char(strtok(" ", " "));
ff.amount = atoi(strtok(" ", "\n"));
return ff;
}
Please find our many mistakes, or perhaps give us some helpful hints.
-
Boooo. Here's the easy fix:
1) Use binary files.
2) Use fread.
3) Be amazed at how easy this was.
fread( &ff, sizeof( fastfood ), 1, fptr );
Quzah.
-
Code:
fastfood read_info (FILE *fptr)
{
fastfood ff;
char line[100];
fgets(line, 100, fptr);
ff.code[5] = char(strtok(line, " "));
ff.food_name[13] = char(strtok(" ", " "));
ff.amount = atoi(strtok(" ", "\n"));
return ff;
}
Most of that looks rather nasty...
- what is char? It's a reserved name for one, so it better not be a function.
- check the return from strtok()
- don't use strtok() if you not aware of its side affects (string alteration)
- dont pass structures back from a function.
All that said, Quzah is right, use better file io in the first place. :)