[英]Read /proc/cpuinfo and print matching line in C
我目前正在使用C程序來獲取特定的CPU信息,例如cpu模型或cpu具有多少個內核。
在Linux上,一種方法是讀取“ / proc / cpuinfo”。 問題:我不希望所有內容都被打印出來。 我只想打印出包含“模型名稱”和“ cpu核心”的行。
#include <stdio.h>
int main() {
char cpuinfo;
FILE *fp = fopen("/proc/xcpuinfo", "r");
if (fp == NULL) {
fprintf(stderr, "Error opening file\n");
} else {
while ((cpuinfo = fgetc(fp)) != EOF) {
printf("%c", cpuinfo);
}
fclose(fp);
}
return 0;
}
使用POSIX getline
簡單解決方案:
#define _GNU_SOURCE
#include <stdio.h>
#include <string.h>
#include <assert.h>
#include <errno.h>
#include <stdlib.h>
int main() {
FILE *fp = fopen("/proc/cpuinfo", "r");
assert(fp != NULL);
size_t n = 0;
char *line = NULL;
while (getline(&line, &n, fp) > 0) {
if (strstr(line, "model name") || strstr(line, "cpu cores")) {
printf("%s", line);
}
}
free(line);
fclose(fp);
return errno;
}
如果沒有getline
,則可以使用足夠大的行緩沖區char buf[200];
並使用fgets(buf, sizeof(buf), fp)
或自己實現一個簡單的getline
。
另一種選擇是將文件名和術語作為搜索的參數傳遞給程序,而不是硬編碼文件名和搜索詞。 使用搜索字詞,您可以使用strncmp
與每個字符串中相同數量的前導字符進行比較,並輸出任何匹配的行(或存儲它們等)。
盡管fgetc
只能讀取一個字符,但fgets
(如POSIX getline
)是面向行的輸入函數,並且一次可以讀取整行(提供足夠大小的緩沖區- 不要跳過緩沖區大小 )
將所有內容放在一起,以便程序將要讀取的文件名作為第一個參數,然后將任意數量的搜索詞(達到argv
的限制)作為后續參數,您可以執行以下操作:
#include <stdio.h>
#include <string.h>
#define MAXC 2048 /* if you need a constant, #define one (or more) */
int main (int argc, char **argv) {
char buf[MAXC]; /* buffer to hold each line in file */
FILE *fp = argc > 1 ? fopen (argv[1], "r") : NULL; /* open file */
if (!fp) { /* validate file open for reading */
perror ("file open failed");
return 1;
}
while (fgets (buf, MAXC, fp)) { /* read each line */
for (int i = 2; i < argc; i++) { /* loop over terms */
char *cmpstr = argv[i]; /* compare string */
size_t cmplen = strlen (cmpstr); /* length to compare */
if (strncmp (buf, cmpstr, cmplen) == 0) /* does start match? */
fputs (buf, stdout); /* output string */
}
}
fclose (fp); /* close file */
return 0;
}
使用/輸出示例
$ ./bin/cmpleadingstr2 /proc/cpuinfo "model name" "cpu cores"
model name : Intel(R) Core(TM) i7-2620M CPU @ 2.70GHz
cpu cores : 2
model name : Intel(R) Core(TM) i7-2620M CPU @ 2.70GHz
cpu cores : 2
model name : Intel(R) Core(TM) i7-2620M CPU @ 2.70GHz
cpu cores : 2
model name : Intel(R) Core(TM) i7-2620M CPU @ 2.70GHz
cpu cores : 2
要么
$ ./bin/cmpleadingstr2 /proc/cpuinfo "processor"
processor : 0
processor : 1
processor : 2
processor : 3
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.