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

时间:2017-02-13 15:54:59

标签: c

因为我还是编程新手,所以请耐心等待。我需要阅读/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;
}

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

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

更新

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

#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

我该如何解决?

3 个答案:

答案 0 :(得分:1)

获得行后,请检查它是否以您要查找的密钥字符串开头。

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()此字符串。

答案 1 :(得分:0)

你想要这个:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(void)
{
  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 wen 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 0;
}

这是您的代码,略有修改和一些注释。

请注意,仍有改进的余地。

答案 2 :(得分:0)

使用strtok和strip,修剪以实现上述程序的键值对。这样就可以轻松比较关键和明确的问题逻辑。

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>

char *strip(char *str){
        if(str == NULL){
                return str;
        }
        int j = 0;
        while(str[0] != '\0' && isspace(str[0])){
                j=0;
                while(str[j] != '\0'){
                        str[j] = str[j+1];
                        j++;
                }
        }
        return str;
}

char *trim(char *str){
        if(str == NULL){
                return str;
        }
        int len = strlen(str)-1;
        while(isspace(str[len])){
                str[len]='\0';
                len--;
        }
        return str;
}
int process_line(char *str, char *res_key, char *res_value){
        char *key, *value;
        key = strtok(str, ":");
        value = strtok(NULL, ":");
        if( key && value){
                key = strip(key);
                key = trim(key);
                value = strip(value);
                value = trim(value);
                //printf("%s:%s\n", key, value);
                strcpy(res_key, key);
                strcpy(res_value, value);
        }
}
int main(int argc, char *argv[])
{
        char filename[] = "/proc/cpuinfo";
        char* key = "system type";
        char* value;
        FILE *file = fopen(filename, "r");
        if (file != NULL) {
                char line[2048]={0x00};
                char temp_key[1024]={0x00};
                char temp_value[1024]={0x00};
                while (fscanf(file, " %[^\n]s", line) != EOF) /* read a line from a file */ {
                        process_line(line, temp_key, temp_value);
                        if(strcmp(temp_key, key) == 0){
                                break;
                        }
                        memset(line, 0x00, sizeof(line));
                        memset(temp_key, 0x00, sizeof(temp_key));
                        memset(temp_value, 0x00, sizeof(temp_value));
                }
                fclose(file);
                printf("model:%s\n", temp_value);
        }
        else {
                perror(filename); 
        }
        return 0;
}

我认为这应该可以解决你的问题