Trozan
Trozan

Reputation: 109

Read name value pairs from a file in C

I want to open a .txt file in C and read the name value pairs in the .txt file and each value in a different variable. The txt file has only 3 lines.

Name1 =  Value1
Name2 =  Value2
Name3 =  Value3

I want to extract the values corresponding to name 1, 2 and 3 and store them in a variable. How do I go about it?

Upvotes: 6

Views: 7477

Answers (3)

apgp88
apgp88

Reputation: 985

You can read file line by line using fgets function. Gives every line in a string. Then use strtok function to Split string into tokens using space as a delimiter. So you will get Value1,Value2...

Upvotes: 1

franka
franka

Reputation: 1927

Create a pointer for the file.

FILE *fp;
char line[3];

Open the file.

fp = fopen(file,"r");
if (fp == NULL){
  fprintf(stderr, "Can't open file %s!\n", file);
  exit(1);  
}

Read content line by line.

for (count = 0; count < 3; count++){      
   if (fgets(line,sizeof(line),fp)==NULL)
      break;
   else {               

      //do things with line variable

      name = strtok(line, '=');
      value = strtok(NULL, '=');



  }  
} 

Don't forget to close the file!

fclose(fp);   

Upvotes: 0

PearsonArtPhoto
PearsonArtPhoto

Reputation: 39698

The best way is shown in this answer

#include <string.h>

char *token;

char *search = "=";

 static const char filename[] = "file.txt";
FILE *file = fopen ( filename, "r" );
if ( file != NULL )
{
  char line [ 128 ]; /* or other suitable maximum line size */
  while ( fgets ( line, sizeof line, file ) != NULL ) /* read a line */
  {
    // Token will point to the part before the =.
    token = strtok(line, search);
    // Token will point to the part after the =.
    token = strtok(NULL, search);
  }
  fclose ( file );
}

I'll leave the rest for you to do.

Upvotes: 4

Related Questions