简体   繁体   English

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

[英]C Program - How to read a file and store its texts in a variable?

Please bear with me since I'm still new in programming.请耐心等待,因为我还是编程新手。 I need to read /proc/cpuinfo to determine a router's model, the file looks like this:我需要阅读/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

What I need to store in a variable is this part bcm63xx/HW553 (0x6358/0xA1) .我需要存储在变量中的是这部分bcm63xx/HW553 (0x6358/0xA1) It is the model number and it changes constantly, here's what I have tried so far:这是型号,它不断变化,这是我迄今为止尝试过的:

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

But that script only prints the file, I don't know how to store the router's model in a variable, how should I do it?但是那个脚本只打印文件,我不知道如何将路由器的模型存储在变量中,我该怎么做?

PS: After storing the router's model in a variable I need to compare it whether it matches the pre-defined variable or not. PS:将路由器的模型存储在变量中后,我需要比较它是否与预定义的变量匹配。

UPDATE更新

I'm trying to make it a function, my code is:我试图使它成为一个函数,我的代码是:

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

But I get an error:但我收到一个错误:

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

How do I fix it ?我如何解决它 ?

Once you have your line, check that it starts with the key string you're looking for.一旦你有了你的行,检查它是否以你正在寻找的关键字符串开头。

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

Once you've identified the line, find the first colon.确定该行后,找到第一个冒号。

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

Now you have the value, although it will include the leading colon and space, so you can iterate past those.现在你有了这个值,虽然它会包含前导冒号和空格,所以你可以遍历它们。

value += 2; 

And then you should be able to use this result.然后你应该能够使用这个结果。 Note that I have not allocated any new space.请注意,我没有分配任何新空间。 If you want to save this value somewhere, then you'll need to copy the string.如果您想将此值保存在某处,则需要复制该字符串。 The easiest way to do this is to duplicate it.最简单的方法是复制它。

char* router_model = strdup(value);

You will have to free() this string once you are finished with it.一旦你完成它,你将不得不free()这个字符串。

You want this:你要这个:

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

This is your code with slight modifications and some comments.这是稍加修改和一些注释的代码。

Note that there is still room for improvement.请注意,仍有改进的余地。

using strtok and strip, trim for achieve key value pair of above program.so that easy compare of key and clear logic of problem.使用strtok和strip,trim实现上面程序的键值对。这样键的比较容易,问题的逻辑清晰。

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

I think this should solve your problem我认为这应该可以解决您的问题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM