gpt4 book ai didi

c - 使用 proc/cpuinfo 查找vendor_id

转载 作者:行者123 更新时间:2023-11-30 20:21:05 34 4
gpt4 key购买 nike

我有以下代码:

#include <stdio.h> 
#include <string.h>
char* get_cpu_vendor_id ()
{

FILE* fp;
char buffer[1024];
size_t bytes_read;
char* match;
char* vendor_id;

fp = fopen ("/proc/cpuinfo", "rb");

bytes_read = fread (buffer, 1, sizeof (buffer), fp);

fclose (fp);


if (bytes_read == 0 || bytes_read == sizeof (buffer))
return 0;

buffer[bytes_read] == '\0';

match = strstr (buffer, "vendor_id");
printf("%s", match);

if (match == NULL)
return 0;

sscanf (match, "vendor_id : %s", vendor_id);
return vendor_id;

}

int main ()
{
printf ("Vendor ID Of The Processor: %s\n", get_cpu_vendor_id ());

return 0;
}

它工作正常,但我不想打印整堆信息,所以当我删除语句时 printf("%s", match); function get_cpu_vendor_id() 返回任意值我无法理解错误

最佳答案

sscanf (match, "vendor_id : %s", vendor_id);

您没有空间存储字符串,请在使用sscanf之前预留空间:

vendor_id = malloc(some_size);

这里:

buffer[bytes_read] == '\0';

您正在将尾随字符与 0 进行比较,您想要:

buffer[bytes_read] = '\0';

最后,请注意,在本例中,"%s" 在第一个空白字符处停止扫描

vendor_id   : GenuineIntel

它在:之后停止,使用"%[^\n]"消耗整行。

关于c - 使用 proc/cpuinfo 查找vendor_id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43861885/

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