I am trying to parse a csv file with C, where the delimiter is |
using strtok
. The problem is that some fields are empty, and therefore the two delimiters are located next to each other. It seems to strtok
just skip all the empty fields and just display the next non-empty field.
The fact is that I need to know in which position the token that is being read belongs.
Here is a small example to illustrate.
FILE
node|171933|||traffic_signals|||||40.4200658|-3.7016652
This line, for example, has 10 fields, but only the field 1,2,9 and 10 has some value in it.
CODE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void main()
{
FILE *fp;
char lineBuf[128];
char *token;
int i=0;
if((fp = fopen("test.txt", "r"))==NULL){
fprintf (stderr, "\nError when opening file\n");
return ;
}
fgets (lineBuf, sizeof(lineBuf), fp);
token=strtok(lineBuf, "|\n");
while(token!=NULL){
printf("Element %d: %s\n",i,token); i++;
token=strtok(NULL, "|\n");
}
}
EXIT
Element 0: node
Element 1: 171933
Element 2: traffic_signals
Element 3: 40.4200658
Element 4: -3.7016652
EXPECTED EXIT
Element 0: node
Element 1: 171933
Element 4: traffic_signals
Element 9: 40.4200658
Element 10: -3.7016652
Is there any other way to parse a string like this, as expected? The number of elements in a row is not defined previously.
, , strtok
, , , .