comp.lang.c FAQ list
How can I read data from
data files with particular formats?
How can I read ten floats without having to use a jawbreaker
"%f %f %f %f %f %f %f %f %f %f"?
How can I read an arbitrary number of fields from a line into an array?
In general, there are three
of parsing data lines:
fscanf or sscanf,
an appropriate format string.
Despite the limitations
mentioned in this section
(see question 12.20),
the scanf family is quite powerful.
Though whitespace-separated fields are always the easiest to
scanf format strings can also be used
column oriented, FORTRAN-style data.
For instance, the line
(See also the last example in question 12.19.)
- Break the line into
fields separated by
(or some other delimiter),
using strtok or the equivalent
(see question 13.6),
then deal with each field individually,
perhaps with functions like atoi
(Once the line is broken up,
the code for handling the fields
is much like the traditional code in main()
for handling the argv array;
see question 20.3.)
This method is particularly useful
for reading an arbitrary
(i.e. not known in advance)
of fields from a line into an array.
Here is a simple example
which copies a line of
up to 10
(separated by whitespace)
into an array:
#define MAXARGS 10
char line = "1 2.3 4.5e6 789e10";
int ac, i;
ac = makeargv(line, av, MAXARGS);
for(i = 0; i < ac; i++)
array[i] = atof(av[i]);
(See question 13.6
for the definition of makeargv.)
- Use whatever pointer manipulations
and library routines
to parse the line in an
(The ANSI strtol and strtod functions
are particularly useful for this style of parsing,
because they can return a pointer
indicating where they stopped reading.)
is obviously the most general way,
but it's also the most difficult and error-prone:
those which use lots of
little pointers to pick apart strings.
possible, design data files and input formats
so that they don't require arcane manipulations,
be parsed with easier techniques
such as 1 and 2:
dealing with the files will
much more pleasant
about this FAQ list