繁体   English   中英

如何阅读文本文件的特定部分?

[英]How can I read a specific part of a text file?

在C语言中,我能够读取如下文本文件的特定部分:

game_results new_statistic(FILE* input, int* rounds) {
    game_results out;

   char temp[300];
   if(fgets(temp, 300, input) != NULL) {
      if(strlen(temp) < 3) {
         fgets(temp, 300, input);
         ++*rounds;
      }

   /* Sorting the string and giving all the variables to the struct game_results */
   sscanf(temp, "%s %d / %d %s %s - %s %d - %d %lf" , out.weekday, &out.date_day, &out.date_month, out.timet,
   out.hometeam, out.awayteam, &out.home_goal, &out.away_goal, &out.crowd);
   out.rounds = *rounds;
   }
   return out;
}

如何在C#中做到这一点?

我需要文本文件中的特定信息。 我想读取“房间数量”的值,然后程序需要知道第一个房间名称为“ Stue”,并具有值1,该值表示房间中的电源连接器。 接下来,它将显示为“ tv”,然后是200(电源),以及3(待机)。 然后,它将对房间的厨房执行相同的操作。

文件中的文本如下所示:

Amount of Rooms: 2
Stue, 1
tv, 200, 3
Kitchen, 1
Fridge, 100, 2

您可以使用File.ReadLines方法打开文件并查询所需的数据,并且该文件仅读取足以满足您查询条件的行。

因此,要获取第一行,请使用LINQ的First()方法,然后在冒号上分割并获取数字。

var rooms = Convert.ToInt32(File.ReadLines(@"c:\yourFile.txt").First().Split(':').Last());

要获得其余的信息,您可以采用几种不同的方法。 我更喜欢LINQ,所以这是另一个例子。

阅读第一行的所有内容(跳过该行),然后在逗号上分割并创建字典。

var data = (from f in File.ReadLines(@"c:\yourFile.txt").Skip(1)
            let parts = f.Split(',')
            select new { key = parts[0], value = Convert.ToInt32(parts[1]) })
          .ToDictionary(x => x.key, x => x.value);

如果信息每次都在同一行上,那么使用Streamreader的简单方法就是

        System.IO.StreamReader file = new System.IO.StreamReader(@"C:\Users\Public\TestFolder\EXPORT.TXT");
        while (file.Peek() != -1)
        {
            line = file.ReadLine();
            string test1;
            string readdate;
            test1 = line.Substring(0, 8);//1
            FullName = line.Substring(8, 20);//2
            Address = line.Substring(28, 20);//3
            ModuleNumber = line.Substring(48, 10);//4
            test1 = line.Substring(58, 4);//5
            ReadType = line.Substring(62, 1);//6
            Service = line.Substring(63, 1);//7
            test1 = line.Substring(64, 1);//8
            test1 = line.Substring(65, 2);//9
            test1 = line.Substring(67, 9);//10
       }

这个特定的代码是我用来读取固定宽度文件的代码,但是您可以将每一行添加到列表中,我认为如果文本文件采用固定宽度或定界格式会更好。

编辑:我很想能够在评论中提出这个建议,但是由于我不允许发表评论,因此我将其作为一个更详细的答案。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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