[英]Parsing a binary file with multiple data types into an array
我創建了多個二進制文件,每個文件包含2個字符串,2個字符,1個double和1個int。 讀取時的數據為
Fokker DR 1
Germany
D
A
1000.0
13
我正在嘗試將dat文件解析為數組,以便可以使用適當的名稱(例如,
Name: Fokker DR 1
Country: Germany
Attack Mode: D
Turn Mode: A
etc.
但是我遇到了麻煩,因為當嘗試使用StreamReader並在空白的每個實例處分割二進制文件時,由於名稱(Fokker DR 1)包含不應分割的多個空格的事實,我遇到了問題。
這是我嘗試分割的代碼:
if (file.Contains("plane1"))
{
StreamReader reader = new StreamReader("plane1.dat");
string line;
while ((line = reader.ReadLine()) != null)
{
string[] data = line.Split(' ');
bin.ReadBinary("plane1.dat");
Console.WriteLine("Name: " + data[0]);
Console.WriteLine("Country: " + data[1]);
Console.WriteLine("Turn Mode: " + data[2]);
Console.WriteLine("Attack Mode: " + data[3]);
Console.WriteLine("Cost: " + data[4]);
Console.WriteLine("Max Damage: " + data[5]);
}
}
有沒有什么方法可以在不同數據類型的每個實例處進行拆分,或者還有另一種方法來標記我的二進制文件中的數據?
BinaryFormatter
將不處理該文件格式。 鑒於其體積小巧和簡單明了的規格,一些超自然的讀取邏輯應該可以解決問題。
如果使用BinaryReader
打開文件,則可以自行決定如何處理下一個或多個要讀取的字節。 如果文件格式不復雜,則很容易做到。 根據您的規格,我創建了以下代碼來讀取您的文件:
using(var br = new BinaryReader(
File.Open(@"c:\tmp\plane.dat", FileMode.Open),
Encoding.ASCII))
{
while(br.BaseStream.Position < br.BaseStream.Length)
{
var name = br.ReadString();
var country = br.ReadString();
var turnmode = br.ReadChar();
var attackmode = br.ReadChar();
var cost = br.ReadDouble();
var maxdamage = br.ReadInt32();
// you can use above vars what ever you need to do
// with them, writing to the console or adding to
// a list for example
// Planes.Add(new Plane {Name = name});
}
}
在測試中,我創建的文件與您的二進制格式匹配。 由於您沒有顯示下一條記錄的開始位置,因此您可能會發現需要進行額外的讀取,例如使用ReadByte
但這取決於您的實際結構。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.