首页 > 解决方案 > c中带有空格的sscanf字符串的替代方法?

问题描述

我正在尝试从 /proc/cpuinfo 文件中检索信息。我已经使用 sscanf 检索了 cpu 核心数。

现在我正在尝试类似地检索模型名称,但这次我 sscanf 没有工作,因为模型名称是一个包含空格的字符串。

有没有其他方法可以检索它?

char *get_cpu_model()
{
   int fp;
   int r;
   char* match;
   char *cpu_model;

   /* Read the entire contents of /proc/cpuinfo into the buffer. */
   fp = open("/proc/cpuinfo",O_RDONLY);

    if (fp == -1) 
   {   
       printf("Error! Could not open file\n"); 
       return 0;
   } 
    while( r != EOF){

       r = ReadTextLine(fp, buffer, BUFFER_SIZE);
    //    printf("%d %s\n", buffer_size, buffer);
       match = strstr (buffer, "model name");

       if (match !=NULL){
            /* Parse the line to extract the clock speed. */
            sscanf (match, "model name : %s", cpu_model);
            break;
       }
   }
   close(fp);

   return cpu_model;
}

proc/cpuinfo 文件如下所示:

processor:0
cpu core :1
model name: Intel(R) Core(TM) i7-6700K CPU @ 4.00GHz

标签: cstringparsingproc

解决方案


您对模型名称的终止条件是“直到行尾”。大概ReadTextLine读取整行。因此,您需要做的就是找到模型名称的开头并strcpy从那里找到它:

match = strstr(buffer, "model name: ");
// ... match points to "model name: XXX"
if(match) {
    match += strlen("model name: ");
    // ... match points to "XXX"
    strcpy(cpu_model, match);
}

但是请注意,您的代码在使用cpu_model时未对其进行初始化,这是一个错误。您应该将其转换为参数,以便调用者为您提供缓冲区,或者用于cpu_model = strdup(match)在堆上分配结果。

正如@bruno 指出的那样,您也在r初始化之前使用它。正确的条件是:

while(ReadTextLine(fp, buffer, BUFFER_SIZE) != EOF)

这样您在获得EOF并且根本不需要r时立即退出。


推荐阅读