简体   繁体   English

在C中使用strtok解析文件

[英]Parsing a file with strtok in C

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). 当它到达“ visgroups”时,它应该停止,这是我要测试的文件的第9行(位于名为* source的缓冲区中)。 "versioninfo" is the first line. 第一行是“ versioninfo”。 When I run this code it just repeatedly prints out "versioninfo" until I cancel the program manually. 当我运行此代码时,它只是反复打印出“ versioninfo”,直到我手动取消程序为止。 Why isn't the strtok function moving on? 为什么strtok函数没有继续运行?

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? 这与strtok不是线程安全的事实有关吗? I'm not using source in any other threads. 我没有在任何其他线程中使用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);
}

Your delims array needs to be nul terminated. 您的delims数组需要终止。 Otherwise how can strtok know how many separators you passed in? 否则, strtok如何知道您传入了多少个分隔符? Normally you'd just use const char *delims = "\\t\\n " but you could simply add ..., 0 to your initializer. 通常,您只需要使用const char *delims = "\\t\\n "但是您可以简单地将..., 0添加到初始化程序中。

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. 在使用要标记化的字符串首次调用strtok之后,所有后续调用都必须将第一个参数设置为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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM