請耐心等待,因爲我仍然是編程新手。我需要閱讀/proc/cpuinfo
確定路由器的型號,文件看起來像這樣:C程序 - 如何讀取文件並將其文本存儲在變量中?
system type : bcm63xx/HW553 (0x6358/0xA1)
machine : Unknown
processor : 0
cpu model : Broadcom BMIPS4350 V1.0
BogoMIPS : 299.26
wait instruction : yes
microsecond timers : yes
tlb_entries : 32
extra interrupt vector : yes
hardware watchpoint : no
isa : mips1 mips2 mips32r1
ASEs implemented :
shadow register sets : 1
kscratch registers : 0
core : 0
VCED exceptions : not available
VCEI exceptions : not available
我需要一個變量來存儲是這部分bcm63xx/HW553 (0x6358/0xA1)
。它的型號,它在不斷的變化,這是我迄今爲止嘗試:
#include <stdio.h>
int main (void)
{
char filename[] = "/proc/cpuinfo";
FILE *file = fopen (filename, "r");
if (file != NULL) {
char line [1000];
while(fgets(line,sizeof line,file)!= NULL) /* read a line from a file */ {
fprintf(stdout,"%s",line); //print the file contents on stdout.
}
fclose(file);
}
else {
perror(filename); //print the error message on stderr.
}
return 0;
}
但該腳本只打印文件,我不知道如何將路由器的模型存儲在一個變量,應該如何我這麼做?
PS: 將路由器模型存儲在一個變量中後,我需要比較它是否與預定義的變量相匹配。
UPDATE
我想使它成爲一個功能,我的代碼是:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char* model() {
char filename[] = "/proc/cpuinfo";
char* key = "system type";
char* value;
FILE *file = fopen(filename, "r");
if (file != NULL) {
char line[1000];
char* router_model = NULL;
while (fgets(line, sizeof line, file) != NULL) /* read a line from a file */ {
fprintf(stdout, "%s", line); //print the file contents on stdout.
if (strncmp(line, key, strlen(key)) == 0) {
char* value = strchr(line, ':');
value += 2;
router_model = strdup(value);
break; // once the key has been found we can stop reading
}
}
fclose(file);
if (router_model != NULL) {
printf("The model is %s\n", router_model); // print router model
}
else {
printf("No %s entry in %s\n", key, filename); // key not found, print some error message
}
free(router_model);
}
else {
perror(filename); //print the error message on stderr.
}
return router_model;
}
int main(void)
{
char* ret;
ret = model();
printf("Model: %s\n", ret);
return 0;
}
但我得到一個錯誤:
test.c: In function ‘model’:
test.c:37:9: error: ‘router_model’ undeclared (first use in this function)
return router_model;
^~~~~~~~~~~~
test.c:37:9: note: each undeclared identifier is reported only once for each function it appears in
如何解決呢?
1.讀通過line.2線。使用strtok使其成爲關鍵值對。通過將鍵與預定義鍵進行比較來查找所需的值。 – rajesh6115
在你的文章的第三個版本中,我看到'router_model'聲明瞭,但是你也包含了關於這個的錯誤文本,這不在你的文章的第一個版本中。你能否確認錯誤信息仍然發生,在'line'聲明之後立即執行'router_model'聲明? – donjuedo