[Courses] [C] Beginner's Lesson: How do I...?
kwmelvin at intrex.net
Fri Dec 13 15:49:45 EST 2002
My question is: How do I read a sequential text file and do a formatted
output of "records" that have a newline delimiter, which consist of four
Tab delimited "fields"? The function strtok() is in strings.h, but it
is a rather complex thing to deal with. Here is an example that reads
from a string array that is in the program:
char records = "rec 1 fld 1 rec1 fld2 rec1 fld3 rec 1 fld 4\nrec2 fld1 rec 2 fld 2 rec2 fld3 rec2 fld4\nrec3 fld1 rec3 fld2 rec 3 fld 3 rec3 fld4\n";
char delimiters = "\t";
field = strtok(records, delimiters); /* find first field */
while (field != NULL)
field = strtok(NULL, delimiters); /* find next field */
Okay, the fact that this works with a string array suggests a possible
solution: Somehow copy the file to a string array and make sure it ends
with a NULL. Perhaps this string array could be called a "buffer"?
Then it might be possible to use strtok() with "\n" as the delimiter
to get a record? Then use strtok() with "\t" as a delimiter to get each
field and assign each one to a separate array (like fld1, fld2...)?
Then I might be able to do something in a printf() to format the output
of each field?
Am I even approaching this problem in a manner that might work? It
seems like a lot of work, but then again, C is known for being hard
to work with when it comes to strings.
I've found an example that does ALMOST what I want to do, except it
creates a random-access file that contains the records. The program
does create a text file of the data in the random-access file. But like
I said, it ALMOST does what I want.... I want to be able to read and
do a formatted output from a plain text file. I'm beginning to think
that I need to look at the source code of "less" or "cat". I wonder
where THAT is? fileutils? (Aside: Yes, the source code is free, but YOU
have to FIND IT if you want to look at it! 8^D)
More information about the Courses