Read name value pairs from a file in C

c, file

Solution

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.

Problem

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?

Original source

Related problems