【问题标题】:Read name value pairs from a file in C从 C 中的文件中读取名称值对
【发布时间】:2012-11-15 01:10:50
【问题描述】:

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

Name1 =  Value1
Name2 =  Value2
Name3 =  Value3

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

【问题讨论】:

  • 我编辑了我认为你想要的格式,但我不确定。基本上我去掉了绒毛。

标签: c file


【解决方案1】:

最好的方法显示在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 );
}

剩下的交给你去做。

【讨论】:

    【解决方案2】:

    您可以使用 fgets 函数逐行读取文件。给出字符串中的每一行。 然后使用 strtok 函数将字符串拆分为使用空格作为分隔符的标记。 所以你会得到 Value1,Value2...

    【讨论】:

      【解决方案3】:

      为文件创建一个指针。

      FILE *fp;
      char line[3];
      

      打开文件。

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

      逐行阅读内容。

      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, '=');
      
      
      
        }  
      } 
      

      别忘了关闭文件!

      fclose(fp);   
      

      【讨论】:

        猜你喜欢
        • 2016-11-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-07-21
        • 2011-06-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多