从 C 中的文件中读取名称值对

Tro*_*zan 5 c file

我想在 C 中打开一个 .txt 文件并读取 .txt 文件中的名称值对以及不同变量中的每个值。txt 文件只有 3 行。

Name1 =  Value1
Name2 =  Value2
Name3 =  Value3
Run Code Online (Sandbox Code Playgroud)

我想提取与名称 1、2 和 3 对应的值并将它们存储在变量中。我该怎么办?

Pea*_*oto 4

这个答案显示了最好的方法

#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 );
}
Run Code Online (Sandbox Code Playgroud)

剩下的事情就交给你来做吧。