I’m trying to write a function that reads in a line from a file using fgets().
After reading the line, I want to take the line apart and make it into smaller strings.
Depending on the first word in the line, the line that I read in can have 3-5 smaller strings that are separated by a white space.
Example:
Line: remove apple 12345
string1: remove
string2: apple
string3: 12345
Line: add tomato red leaf
string1: add
string2: tomato
string3: red
string4: leaf
From the example above, if 1st string is remove, I need to read 2 other strings (apple, 12345).
If the first string is add, I need to read 3 other strings (tomato, red, leaf).
Is there anyway that I can decide the number of times to read and do this using sscanf?
while( fgets( buf, sizeof buf, course_file ) != NULL ){
sscanf( buf, "%s", &string1);
printf( "%s\n", buf );
}
It is not compulsory that I use sscanf, I’m open to other suggestions.
The function typically used to tokenize strings is
strtok, but it is not thread-safe; its modern version isstrtok_rshould be used instead.Start tokenizing the
bufin the first call, check the first token, and then go into one of several loops that depend on the content of the first token: