gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 21:08:40 25 4
gpt4 key购买 nike

我正在 Linux 提示符下执行“dmidecode”命令,该命令将提供产品信息。我想将产品名称和制造商名称存储到两个单独的变量中。我正在使用 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;

}

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

最佳答案

工作代码:

#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;
}

关于c 程序将 show 命令输出存储到字符串中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37318129/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com