我正在写一个简短的函数来通过检查字符串标记来解析文件。它应该在它到达“visgroups”时停止,这是我用来测试的文件的第9行(在缓冲区中称为* source)。 “versioninfo”是第一行。当我运行此代码时,它只是重复打印出“versioninfo”,直到我手动取消程序。为什么strtok功能不继续?
当我到达这一点时,我将对源进行一些不同的操作,这就是循环控制变量被称为“活动”的原因。这与strtok不是线程安全的事实有什么关系吗?我没有在任何其他线程中使用source。
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);
}
答案 0 :(得分:3)
您的delims
数组需要终止。否则strtok
怎么知道你传入了多少个分隔符?通常情况下,您只需使用const char *delims = "\t\n "
,但只需将..., 0
添加到初始值设定项即可。
答案 1 :(得分:2)
在第一次使用要标记的字符串调用strtok
之后,必须在第一个参数设置为NULL的情况下完成所有后续调用。
temp = strtok(NULL, delims);
并且它没有必要对线程安全做任何事情。
尝试像这样重写:
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);
}