gpt4 book ai didi

C 程序 - 如何读取文件并将其文本存储在变量中?

转载 作者:太空宇宙 更新时间:2023-11-03 23:42:11 26 4
gpt4 key购买 nike

请多多包涵,因为我还是编程新手。我需要阅读 /proc/cpuinfo 来确定路由器的型号,该文件如下所示:

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;
}

但是那个脚本只打印文件,我不知道如何将路由器的模型存储在变量中,我应该怎么做?

附言:将路由器的模型存储在变量中后,我需要比较它是否与预定义变量匹配。

更新

我试图让它成为一个函数,我的代码是:

#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

我该如何解决?

最佳答案

一旦你有了你的行,检查它是否以你要查找的键字符串开头。

char* key = "system type";
...
if (strncmp(line, key, strlen(key)) == 0) {
/* this is the line you want */
}

确定该行后,找到第一个冒号。

char* value = strchr(line, ':');

现在您有了值,尽管它会包含前导冒号和空格,因此您可以迭代过去。

value += 2; 

然后你应该可以使用这个结果。请注意,我没有分配任何新空间。如果您想将此值保存在某处,则需要复制该字符串。最简单的方法是复制它。

char* router_model = strdup(value);

您必须在完成后free() 这个字符串。

关于C 程序 - 如何读取文件并将其文本存储在变量中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42208204/

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