[Courses] RE: Next C topic

James jas at spamcop.net
Thu Jul 18 17:53:50 EST 2002


On Thu, 18 Jul 2002, Young, Amber wrote:

> Mary,
> 
> I would appreciate some guidance on reading from an external file.  I have a
> long list of input in the form: 00 00 00.00  I'm not sure how best to read
> this in, I thought maybe an array, but the first two numbers are integers
> while the third is real.

Sounds like a job for "struct" in C. Something like:

struct entry
{
   unsigned int first;
   unsigned int second;
   double third;
};

would do the job. You could make it a typedef, like this:

typedef struct
{
/* (same three lines from above) */
} entry;

which allows you to treat "entry" like a normal type in C:

entry file_contents[1024];


Then you can assign values to the "fields" within that struct like this:

file_contents[0].first = 7;
file_contents[0].second = 24;
file_contents[0].third = 15.39;


You can modify the example program given earlier on this list to parse 
each line into the three fields. One caveat: make sure your array is big 
enough to hold every line of your file! Otherwise, you'll write past the 
end of the array, making a nasty mess...


James.




More information about the Courses mailing list