c - 使用 proc/cpuinfo 查找vendor_id

标签 c linux

我有以下代码:

#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/

相关文章:

javascript - 使用nodejs更改系统/操作系统时间

c - 如何检查int输入是否大于2147436647或小于-2147483648?

c - 在 linux 可加载内核模块中重新定位与位置无关的代码

c++ - 回文程序和条件跳转或移动取决于未初始化的值

linux - 删除具有相似名称的文件,除了一个?

linux - Rust `std::time::Instant` "panicked at ' 提供的瞬间晚于 self “

linux - 在 bash 脚本中循环执行命令时,如何将来自 cURL 的响应主体保存在文件中?

c - 数组代码编译错误[c]

c++ - 是否有任何 "penalties"用于在函数内定义结构?

c - C 中 case 范围的语法?