简体   繁体   中英

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:

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) . 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.

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.

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.

#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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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