I have a CSV with 7 Fields
me,val1,val2,val3,val4,val5,val6,
me,val1,val2,val3,val4,val5,val6,
Im parsing this using the following function
void readcsv()
{
lk_dispclr();
lk_disptext(2,0,"Parsing CSV..",0);
lk_disptext(3,0,"Please Wait..",0);
FILE* stream = fopen("input.csv", "r");
if(stream!=NULL)
{
char line[1024];
while (fgets(line, 1024, stream))
{
char *tmp = strdup(line);
char a1[20]= "";
char b1[20]= "";
char c1[20]= "";
char d1[20]= "";
char e1[20]= "";
char f1[20]= "";
char g1[20]= "";
strcat(a1, getcsvfield(tmp, 1));
strcat(b1, getcsvfield(tmp, 2));
strcat(c1, getcsvfield(tmp, 3));
strcat(d1, getcsvfield(tmp, 4));
strcat(e1, getcsvfield(tmp, 5));
strcat(f1, getcsvfield(tmp, 6));
strcat(g1, getcsvfield(tmp, 7));
//printf("Field 1 would be %s\n", a1);
// printf("Field 2 would be %s\n", getcsvfield(tmp, 2));
// printf("Field 2 would be %s\n", getcsvfield(tmp, 3));
// printf("Field 2 would be %s\n", getcsvfield(tmp, 4));
// printf("Field 2 would be %s\n", getcsvfield(tmp, 5));
// printf("Field 2 would be %s\n", getcsvfield(tmp, 6));
execute("INSERT INTO sdata (uid,sid,name,area,type,stbamount,pkgamount) VALUES('%s','%s','%s','%s','%s','%s','%s');",a1,b1,c1,d1,e1,f1,g1);
// NOTE strtok clobbers tmp
free(tmp);
}
lk_dispclr();
lk_disptext(2,4,"CSV Imported!",1);
lk_getkey();
}
else
{
lk_dispclr();
lk_disptext(2,4,"CSV Not Found!",1);
lk_getkey();
}
}
//Used for parsing CSV
const char* getcsvfield(char* line, int num)
{
char buffer[1024]= {0};
strcpy(buffer,line);
const char* tok;
for (tok = strtok(buffer, ",");
tok && *tok;
tok = strtok(NULL, ",\n"))
{
if (!--num)
return tok;
}
return NULL;
}
But if the 6th field (val5
) is missing val6
is getting inserted in the Table at the position for val5
, where it actually should be blank.
What im i doing wrong?
Aucun commentaire:
Enregistrer un commentaire