NJMR
NJMR

Reputation: 1926

Content of CSV file to a structure in C.

I have a structure...

struct myStruct {
    char Topic[8];
    char Unit[8];
    char Prim[1];
    char Temp[2];
    ...
    ...
    ...
    };

I am parsing the data from a csv file. Where each token is a member of the structe in that order.

ptr = fgets( record, MAX_RECORD, fpIn );
strcpy(eachRow, record);
token = strtok(eachRow, ",");
while(token != NULL)
{   
    printf("Token = %s \n", token);
    // I have to copy the token into that members of the structure in that order.
    token = strtok(NULL, ",");
}

How can I map the structuer memebers to pointer so that I can use in a loop to copy the token directly into the member of the structure?

Upvotes: 3

Views: 202

Answers (1)

unwind
unwind

Reputation: 399881

I would just use a static array of offsets, computed at compile-time using offsetof():

static const size_t fields[] = {
  offsetof(struct myStruct, Topic),
  offsetof(struct myStruct, Unit),
  offsetof(struct myStruct, Prim),
  ...
};

Then step through that as you tokenize each field. Of course you can make it better by also including the maximum field size to prevent overwrites.

Also please note that in general parsing CVS can be harder than you think, so it might be worth using a third-party library to do this if it's critical.

Upvotes: 5

Related Questions