1

リストビューを含むこのexeを作成したので、バイナリファイルを開くと、列にテキストポインターが表示され、別の列にテキスト文字列が表示されます。

「forループ」を使用してポインターを表示することができましたが、ループを使用してテキスト文字列を表示する方法がわからなかったので、使用したいのは、ポインターをループして、それが指すテキストを表示することですまで、各テキストの後に 00 00 で停止します。

これはバイナリファイル構造のサンプルです。

バイナリ ファイルの最初の 4 バイトはポインタ/文字列の量、次の 4 バイト * 最初の 4 バイトはポインタ、残りはテキスト文字列で、各文字列は 00 00 で区切られ、すべて Unicode です。

それで、文字列列の各ポインタの文字列を表示する方法について誰か助けてもらえますか?

編集:バイナリファイルを開くボタンのコードは次のとおりです。

        private void menuItem8_Click(object sender, EventArgs e)
    {
        textBox1.Text = "";
        OpenFileDialog ofd = new OpenFileDialog();
        ofd.Title = "Open File";
        ofd.Filter = "Data Files (*.dat)|*.dat|All Files (*.*)|*.*";
        if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
        {
            MessageBox.Show("File opened Succesfully!", "Info", MessageBoxButtons.OK, MessageBoxIcon.Information);
            path = ofd.FileName;
            BinaryReader br = new BinaryReader(File.OpenRead(path));               
            int num_pointers = br.ReadInt32();
            textBox1.Text = num_pointers.ToString();
            for (int i = 0; i < num_pointers; i++)
            {
                br.BaseStream.Position = i * 4 + 4;
                listView1.Items.Add(br.ReadUInt32().ToString("X"));
            }
            br.Close();
            br = null;
        }
        ofd.Dispose();
        ofd = null;
    }
4

1 に答える 1

0

まず、次のように BinaryReader をインスタンス化するときにエンコーディングを指定します。

BinaryReader br = new BinaryReader(File.OpenRead(path), Encoding.Unicode);

次に、読み取りオフセットのリストを保持します。(後で ListView に追加することもできます):

List<int> offsets = new List<int>();
for (int i = 0; i < num_pointers; i++)
{
    // Note: There is no need to set the position in the stream as
    // the Read method will advance the stream to the next position
    // automatically.
    // br.BaseStream.Position = i * 4 + 4;
    offsets.Add(br.ReadInt32());
}

最後に、オフセットのリストを調べて、ファイルから文字列を読み取ります。後でビューにデータを入力できるように、それらを何らかのデータ構造に入れたい場合があります。

Dictionary<int,string> values = new Dictionary<int,string>();
for (int i = 0; i < offsets.Count; i++)
{
    int currentOffset = offsets[i];

    // If it is the last offset we just read until the end of the stream
    int nextOffset = (i + 1) < offsets.Count ? offsets[i + 1] : (int)br.BaseStream.Length;

    // Note: Under the supplied encoding, a character will take 2 bytes.
    // Therefore we will need to divide the delta (in bytes) by 2.
    int stringLength = (nextOffset - currentOffset - 1) / 2;

    br.BaseStream.Position = currentOffset;

    var chars = br.ReadChars(stringLength);
    values.Add(currentOffset, new String(chars));
}

// Now populate the view with the data...
foreach(int offset in offsets)
{
    listView1.Items.Add(offset.ToString("X")).SubItems.Add(values[offset]);
}
于 2012-09-19T11:14:47.400 に答える