这是扫描下面有关/proc/cpuinfo的信息的代码(而且它可以工作)。使用%*s,我可以跳过存储每一行的特定列。因此,跳过5次之后,我可以存储vendor_id。但是为什么我要跳过4次才能得到cpu家族呢?
{
int fd = open("/proc/cpuinfo", O_RDONLY);
char *buffer = (char *)malloc(BUFF_SIZE);
int length = read(fd, buffer, BUFF_SIZE);
sscanf(buffer, "%*s %*s %*s %*s %*s %s %*s %*s %*s %s %*s %*s %s",
vendor_id, cpu_family, cpu_model);
}

发布于 2021-01-21 20:29:17
您可以通过一个sscanf()调用来实现您的目标,但是它更复杂:
terminator;
H 212F 213// get CPU info into 3 char arrays of at least 100 bytes.
// returns -1 on error, 0
int get_info(char vendor_id[100], char cpu_family[100], char cpu_model[100]) {
char buffer[BUFF_SIZE];
int fd = open("/proc/cpuinfo", O_RDONLY);
int length;
if (fd < 0)
return -1;
length = read(fd, buffer, BUFF_SIZE - 1);
close(fd);
if (length <= 0)
return -1;
buffer[length] = '\0';
if (sscanf(buffer, "%*[^\n] " // skip the processor line
"%*[^:]: %99[^\n] " // skip the legend and parse vendor_id
"%*[^:]: %99[^\n] " // skip the legend and parse cpu family
"%*[^:]: %99[^\n]", // skip the legend and parse model
vendor_id, cpu_family, cpu_model) != 3) {
return -1;
}
return 0;
}https://stackoverflow.com/questions/65835005
复制相似问题