danu wrote
(in article
<11**********************@g43g2000cwa.googlegroups .com>):
I'm trying to read data from a file (line by line) and trying to assign
the values to the structure members. I'm kind of lost in this case
since the books I'm using for reference doesn't give any examples about
this case.
typedef struct{
char magicNum[2];
int width;
int height;
int maxGrey;
int pixels[ROW][COLUMN];
} image
and the file i'm trying to read is looks like this. (it's a .pgm image)
P2
24 7 15
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 3 3 3 3 0 0 7 7 7 7 0 0 11 11 11 11 0 0 15 15 15 15 0
0 3 0 0 0 0 0 7 0 0 0 0 0 11 0 0 0 0 0 15 0 0 15 0
0 3 3 3 0 0 0 7 7 7 0 0 0 11 11 11 0 0 0 15 15 15 15
My question is : If I read the input line by line, how do I assign
values to structure members?
I was trying to use some approach like:
while(fgets(buffer, MAX, infile)!=NULL){
strcpy(image.magicNum, getWord(buffer, MAX);
image.width= getWord(buffer, MAX);
You need to parse the lines into subcomponents, and decide which
structure element is associated with which components. You
probably need some error checking code in there as well.
It's a bit of a pain, but there is a standard function which is
used for this sort of thing, strtok(). It has some unexpected
side-effects for the newcomer, so be sure and read the docs
carefully. Once you have the input line broken into pieces, you
then have to convert them into the correct data type for storing
in the array. strtol() and company might be helpful for some of
this.
There have been a lot of 'alternatives' to strtok() coded up
that are easier to use, which you might investigate, but you
need one in source form to have a shot at your code being
portable.
Another approach is to read in the characters one at a time
instead, and parse them by hand as you go, using fgetc()
instead. You might or might not find that an easier way to go.
Some folks would use scanf() or sscanf() instead, but that
function has more 'features' than most people learn in a
lifetime, so I wouldn't recommend until you've been involved in
C programming much longer.
Also, if you haven't read it yet, the comp.lang.c FAQ document
might be very helpful to you as a general resource. Reading it
through front to end is an excellent way to jump start your C
knowledge.
http://docs.mandragor.org/files/Prog...es/C/clc_faq_e
n/
--
Randy Howard (2reply remove FOOBAR)
"The power of accurate observation is called cynicism by those
who have not got it." - George Bernard Shaw