Rob111b@gmail.com said:
Quote:
Hi there,
>
I need to make a piece of code in C that
>
1. opens a specified file,
2. Reads the data in the file and separates it as shown below,
3. Converts the strings into integers and then perfoms some
manipulation on them,
4. returns the new values to a second text file (possibly, not quite
sure on this one yet).
>
My data is given in the following format (there is one space between
a1 and b1, b1 and c1, etc.):
x
y
a1 b1 c1 d1 e1 f1
a2 b2 c2 d2 e2 f2
while not EOF
Look up fgets and strtol in your C book.
fgets reads a line from a file (if the line isn't too long - if you know
how long your lines are, just make sure you define your array to be
that long plus a few.
strtol converts a string to an integer, and - rather wonderfully -
provides a mechanism for telling you where to continue parsing after
it's done. Very useful in this context.
If you don't know in advance how many rows you have, you will need to
use dynamic allocation for your arrays, and be prepared to realloc from
time to time.
I suspect that x and y will give you that info, though - presumably
that's what they're for?
Anyway, here's your strategy: use fgets and strtol - one after the
other! Don't try to combine them in one call! - to get x. Then do it
again to get y. Don't worry about code repetition at this stage. It's
easier than trying to shoehorn those reads into the main loop.
Now - presumably - use x and y to shape your dynamic array using malloc
(I'm assuming that's what x and y are for, and of course I could be
wrong).
Once you've done that, you are ready for your main loop:
line = 0;
while(fgets(buffer, sizeof buffer, fp) != NULL)
{
char *p = buffer;
char *endl = NULL;
for(datum = 0; datum < x; datum++)
{
array[line][datum] = strtol(p, &endl, 10);
/* here, I'm ignoring the possibility of a duff
data value, but you probably shouldn't. If
endp == p, no conversion was possible.
*/
p = endl + 1;
}
++line;
}
if(line != y)
{
you missed something, I guess!
}
That's about as much help as I can give you without actually doing it
for you. :-)
--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at the above domain, - www.