1

我正在编写一个简短的函数来通过检查字符串标记来解析文件。当它点击“visgroups”时它应该停止,这是我用来测试的文件的第 9 行(位于名为 *source 的缓冲区中)。“版本信息”是第一行。当我运行此代码时,它只是重复打印出“versioninfo”,直到我手动取消该程序。为什么 strtok 函数没有继续运行?

当我达到这一点时,我将对源进行一些不同的操作,这就是循环控制变量被称为“活动”的原因。这与 strtok 不是线程安全的事实有关吗?我没有在任何其他线程中使用源代码。

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);
}
4

2 回答 2

3

您的delims数组需要以 nul 终止。不然怎么strtok知道你传入了多少个分隔符?通常你只是使用const char *delims = "\t\n ",但你可以简单地添加..., 0到你的初始化程序中。

于 2012-11-22T21:15:53.383 回答
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);
}
于 2012-11-22T21:15:09.910 回答