c程序将show命令输出存储到字符串中

时间:2016-05-19 08:42:04

标签: c parsing

我正在执行" dmidecode"在linux提示符下的命令,它将提供产品信息。我想将产品名称和制造商名称存储到两个单独的变量中。我正在使用popen来执行命令。

实施例: 使用popen(dmidecode) 输出如下。

系统信息

    ------snip--------
    Manufacturer: Hewlett-Packard
    Product Name: HP Compaq 1234 Elite SFF PC
    Version: Not Specified
    Serial Number: 123456

我想将制造商信息存储到一个变量中,将产品名称存储到另一个变量中。

您能否提出实施上述方案的想法?

我没有完全编写代码,示例代码如下。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
    FILE *fpipe;
    char *command = "dmidecode";
    char ch[50],manufacturer[50],productname[50];

    if ((fpipe = popen(command, "r")) == NULL)
    {
        printf("popen() failed.");
        exit(1);
    }

    //read line by line
    while (fgets(ch,sizeof ch,fpipe))
    {
        // need to code
        printf("%s", ch);
    }
    pclose(fpipe);
    return -1;

}

我想解析输出并仅获取制造商和产品信息。

2 个答案:

答案 0 :(得分:0)

您可以使用sscanf

sscanf(ch, "Manufacturer: %[^\n]", manufacturer);

它将使用格式字符串ch扫描"Manufacturer: %[^\n]"中的文本。格式字符串告诉sscanf跳过文本的第一部分,Manufacturer:。然后,%[^\n]告诉它将其余部分存储到manufacturer数组变量中。这里需要注意的一件事是,如果输入文字没有匹配格式字符串(不是以Manufacturer:开头),sscanf会报告在其返回值中(0 =&#34;失败&#34 ;; 1 =&#34;解码1字段&#34;)。

所以你可以使用它:

int result;
result = sscanf(ch, "Manufacturer: %[^\n]", manufacturer);
result = sscanf(ch, "Product Name: %[^\n]", product_name);
if (result == 1)
{
    // Just decoded the product name.
    // Must have decoded the manufacturer earlier (if the file format was OK)
    printf("Decoded %s and %s\n", manufacturer, product_name);
}

答案 1 :(得分:0)

工作代码:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
  FILE *fpipe;
  char *command = "dmidecode";
  char ch[100]={0}, manufacturer[50]={0}, productname[50]={0}, *m, *p;

  if ((fpipe = popen (command, "r")) == NULL)
    {
      printf ("popen() failed.");
      exit (1);
    }

  //read line by line
  while (fgets (ch, sizeof ch, fpipe))
    {
      if (m = strstr (ch,"Manufacturer"))
        {
          strcpy (manufacturer, m + strlen ("Manufacturer: "));
        }
      if (p = strstr (ch, "Product Name"))
        {
          strcpy (productname, p + strlen ("Product Name: "));
        }
    }
  pclose (fpipe);
  printf ("%s", manufacturer);
  printf ("%s", productname);
  return 0;
}