-
problem with fgets
Having problems reading info from a data file into an array of structures. The first time through, it gets the origin state and destin city correct, but all the other information is wrong. The origin City is storing the first three letters of the origin city, but also the origin state. (ie BalMD instead of Baltimore).
Also, I'm not sure waht the "200" means in fgets. I've toyed around with that ranging anywhere from 100 to 1000, but still get the same results.
Thanks.
Code:
typedef struct leg
{
char originCity[20];
char originState[3];
char destinCity[20];
char destinState[3];
int nights;
int miles;
}LEG;
struct leg *GetLegInfo (int numLegs, FILE *ifp, LEG *legs)
{
int i;
for (i = 0; i < numLegs; i++)
{
/* fill arrary of legs */
fgets (legs[i].originCity, 200, ifp);
fgets (legs[i].originState, 200, ifp);
fgets (legs[i].destinCity, 200, ifp);
fgets (legs[i].destinState, 200, ifp);
fscanf (ifp, "%d", &legs[i].nights);
fscanf (ifp, "%d", &legs[i].miles);
}
fclose (ifp);
return (legs);
}
-
Your use of fgets is definately wrong in regards to the number you're unclear about (200). That number is the size of the buffer you're reading into. If you had a long line in your file, you'd be getting a segfault as you merrily blow by the ends of your buffers for reading so much.
Read this FAQ entry on how to read a line of text from the keyboard (change 'stdin' to your file pointer to read from a file, the rest of the FAQ entry related to fgets applies). Also read the man page for fgets to see exactly how it works.
In short, fgets reads an entire line from your file into the provided buffer, or stops if the line is longer than the number specified.
Quzah.
-
A better choice would be fread(), or maybe fgetc(). fgets() is meant to read a line of text from a stream, and is not normally used for structs.
Plus, there is the concept of reading from a binary stream - a stream that does not use newlines to mark the end of a record, it uses logical record length instead.
-
Is yor file a sequence of lines (ending in \n) or records of equal size?
If records, jim is correct and fread() would be the function you want. I would assume he's correct and records is the case because you are reading into a structure. The file would therefore be a binary file, so be sure to fopen() it with the "rb" mode.
-
> The origin City is storing the first three letters of the origin city
fgets() stores both a \n and a \0 in the buffer you provide. So if you have "NYC" as your data, you need a char[5] at least to store it in.
> fgets (legs[i].originCity, 200, ifp);
Would be
fgets (legs[i].originCity, sizeof(legs[i].originCity), ifp);
> fscanf (ifp, "%d", &legs[i].nights);
Don't mix fgets() with fscanf()
char temp[100];
fgets (temp, sizeof(temp), ifp);
sscanf (temp, "%d", &legs[i].nights);