簡體   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