Reputation: 221
I'm writing a short function to parse through a file by checking string tokens. It should stop when it hits "visgroups", which is the 9th line of the file I am using to test (which is in the buffer called *source). "versioninfo" is the first line. When I run this code it just repeatedly prints out "versioninfo" until I cancel the program manually. Why isn't the strtok function moving on?
I will be doing some different manipulation of the source when I reach this point, that's why the loop control variable is called "active". Would this have anything to do with the fact that strtok isn't thread-safe? I'm not using source in any other threads.
int countVisgroups(int *visgroups, char *source) {
const char delims[] = {'\t', '\n', ' '};
int active = 0;
char *temp;
while (!active){
temp = strtok(source, delims);
if (temp == NULL) {
printf("%s\n", "Reached end of file while parsing.");
return(0);
}
if (strncmp(temp, "visgroups", 9) == 0) {
active = 1;
return(0);
}
printf("%s\n", temp);
}
return(0);
}
Upvotes: 1
Views: 2122
Reputation: 93760
Your delims
array needs to be nul terminated. Otherwise how can strtok
know how many separators you passed in? Normally you'd just use const char *delims = "\t\n "
but you could simply add ..., 0
to your initializer.
Upvotes: 3
Reputation: 10358
After the first call to strtok
with the string you want to tokenize, all subsequent calls must be done with the first parameter set to NULL.
temp = strtok(NULL, delims);
And no it probably doesn't have to do anything with thread safety.
Try to rewrite it like this:
int countVisgroups(int *visgroups, char *source) {
const char delims[] = {'\t', '\n', ' ', '\0'};
int active = 0;
char *temp;
temp = strtok(source, delims);
while (!active){
if (temp == NULL) {
printf("%s\n", "Reached end of file while parsing.");
return(0);
}
if (strncmp(temp, "visgroups", 9) == 0) {
active = 1;
return(0);
}
printf("%s\n", temp);
temp = strtok(NULL, delims);
}
return(0);
}
Upvotes: 2