Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

parsing 3 different types of text file 1

Status
Not open for further replies.

yoink

Programmer
Dec 2, 2001
15
AU
Hi everyone,

I've written a program that parses csv files using a pretty simple function (using a bit of help from tek-tips I might add). I've had a request to expand the program to use a number of different file formats.

Basically, I've got three different file formats I need to parse. They are as follows:

Type 1 is a space separated file

MAYFIELD DVE
Time Pressure(AVE) Flow West(AVE) Flow East
MWG l/s l/s
17/01/02 13:06:00 42.456 0.000 1.280
17/01/02 13:12:00 43.390 0.000 2.320
17/01/02 13:18:00 43.533 0.000 3.280
etc

Type 2 is a tab separated file

FILE: C:\SPECTRUM\pe5472_5.SPL

Date (dd/mm/yy) Time (hh:mm:ss) MWG
16/01/02 11:33:30 67.471
16/01/02 11:34:30 68.276
16/01/02 11:35:30 67.580

Type 3 is a csv file

16/01/02,11:33:30,67.471
16/01/02,11:35:30,69.471
16/01/02,12:13:30,77.471

Type 1 and 2 files have a number of lines at the top of the files that I want to ignore (all the heading information). Type 1 files have this heading information reappear at random times throughout the file, so I can't just skip over the first 4 lines as they might show up again later in the file.

So, I need to:

a) work out if a file is csv, space delim or tab delim
b) ignore any line that doesn't start with a date field (dd/mm/yy)

Anyone got any suggestions as to how I can go about doing this? Here's what I've got at the moment for parsing csv files (which works fine):

FILE *ptrInputFile=fopen(ansFileName.c_str(),"r");
char chrLine[80];

//Whilst we're able to read lines from the file
while (fgets(chrLine,sizeof chrLine,ptrInputFile))
{
char *ptrValue;
char chrValue[20];

ptrValue = strtok(chrLine, ",");

//first value
if (ptrValue)
{
sprintf(chrValue, "%s", ptrValue);
}

//While ptrValue != NULL, there are more values in the line
while( (ptrValue = strtok(NULL, ",")) != NULL)
{
sprintf(chrValue, "%s", ptrValue);
etc
}

Cheers,

Andrew
 
The following code will work for you.

#include <stdio.h>
#include <string.h>
void main (){
FILE *ptrInputFile=fopen(&quot;test2.txt&quot;,&quot;r&quot;);
char chrLine[80];

while (fgets(chrLine,sizeof(chrLine),ptrInputFile))
{
if (chrLine[0] >='0' && chrLine[0] <= '9'){
char seps[] = &quot; ,\t\n&quot;;
char *token;

token = strtok( chrLine, seps );
while( token != NULL )
{
/* While there are tokens in &quot;string&quot; */
printf( &quot; %s\n&quot;, token );
/* Get next token: */
token = strtok( NULL, seps );
}
}
}
}
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top