Click to See Complete Forum and Search --> : Newbie problem with importing csv file


chadj
February 26th, 2003, 04:24 PM
I urgently need to import a csv file into memory, and process the data. I have done this with "int" only in the past and it has worked well, but need to get some strings into the process and have been struggling to resolve the problem. I need to break up the following line X 500 into the fields below.

The way I see it the fscanf should split where I have commas and slashes, but it does not the first string contains "BF,High,8,2003/01/01" and the rest is garbage. Could someone please point me in the right direction.

CSV File
BF,High,8,2003/01/01 00:00,2003/01/01 00:59,2003/01/01 07:59

Code
while( fscanf(fp, "%s,%s,%s,%d/%d/%d %d:%d,%d/%d/%d %d:%d,%d/%d/%d %d:%d",
incedent[il].catagory,
incedent[il].priority,
incedent[il].level,
&incedent[il].open_year,
&incedent[il].open_month,
&incedent[il].open_day,
&incedent[il].open_hour,
&incedent[il].open_minute,
&incedent[il].respond_year,
&incedent[il].respond_month,
&incedent[il].respond_day,
&incedent[il].respond_hour,
&incedent[il].respond_minute,
&incedent[il].resolve_year,
&incedent[il].resolve_month,
&incedent[il].resolve_day,
&incedent[il].resolve_hour,
&incedent[il].resolve_minute) != EOF )

wbartley
February 26th, 2003, 05:28 PM
I have never had any luck with scanf in this regard. I would use a combination of fgets and strtok to parse your file.

snaebyllej
February 26th, 2003, 05:54 PM
Your problem is that commas are string characters, too. It's taking everything it thinks could make up 1 string and putting it into your first string.

One way to do it is to say what characters you don't wan't in your string:

fscanf(fp, "%[^,],%[^,],%[^,],%[^,],%[^,],%[^\n]",p1,p2,p3,p4,p5,p6);

(where p1-6 are all strings; convert from there as needed).

This way, you're saying to put all characters up to but not including a comma in the first string, and so on.

KabalProg
February 26th, 2003, 05:56 PM
Hi, try the following:


while( fscanf(fp, "%[^,]%*c%[^,]%*c%[^,],%d/%d/%d %d:%d,%d/%d/%d %d:%d,%d/%d/%d %d:%d",
incedent[il].catagory,
incedent[il].priority,
incedent[il].level,
&incedent[il].open_year,
&incedent[il].open_month,
&incedent[il].open_day,
&incedent[il].open_hour,
&incedent[il].open_minute,
&incedent[il].respond_year,
&incedent[il].respond_month,
&incedent[il].respond_day,
&incedent[il].respond_hour,
&incedent[il].respond_minute,
&incedent[il].resolve_year,
&incedent[il].resolve_month,
&incedent[il].resolve_day,
&incedent[il].resolve_hour,
&incedent[il].resolve_minute) != EOF )

KabalProg

chadj
February 26th, 2003, 06:38 PM
Thanks for the response to all of you, I got past it be converting the comma's to spaces for now and it works. I will try with anouther file at a later stage.

Thanks Again