Reputation: 25
I have a txt file with delimiter ';'.
I'm reading this file in C using fgets and tokenizing the fields using strtok.
File record Example -
500;Y;Something error message
My C Structure where I want to load files
typedef errRec{
long id;
char fail_ind;
char error_msg[1000];
}errrec_t;
errRec.id = atol(strtok(fileRec,";"));
strcpy(errRec.fail_ind,strtok(NULL,";"));
strcpy(errRec.error_msg, strtok(NULL,";"));
Question :
strcpy is working correctly for the id and error_msg but not working for the fail_ind which is of character type.
I'm getting warning as -
warning #167: argument of type "YESNOIND_C_T={char}" is incompatible with parameter of type
"char*__restrict__";
strcpy(errRec.fail_ind,strtok(NULL,";"));
How can I store this character from strtok in fail_ind or What are the different ways I can store the character ?
After some suggestions I'm trying to use strsep instead of strtok to handle the NULL values -
char *fileRecPtr;
fileRecPtr = strdup(fileRec);
errRec.id = atol(strtok(&fileRecPtr,";"));
errRec.fail_ind = *(strsep(&fileRecPtr,";"));
strcpy(errRec.error_msg, strsep(&fileRecPtr,";"));
Do you think this approach is correct and especially below line is correct to store Character?
errRec.fail_ind = *(strsep(&fileRecPtr,";"));
Upvotes: 1
Views: 92
Reputation: 753695
If you ignore the risk of program crashes, you could use:
errRec.fail_ind = *strtok(NULL, ";");
That's risky — if strtok()
returns a null pointer, your program probably crashes (and that's true of the other uses of strtok()
). A safer version saves and checks the pointer:
char *ptr = strtok(NULL, ";");
if (ptr == NULL)
…report error; do not continue…
errRec.fail_ind = *ptr;
This does not validate that the failure indicator is a single character; it's your call on whether that matters.
Upvotes: 2