繁体   English   中英

C# BinaryWriter/BinaryReader - 读取器顺序与写入顺序不匹配

[英]C# BinaryWriter/BinaryReader - Reader order doesn't match write order

我有一些体素数据,我想使用 BinaryWriter 保存,然后使用 BinaryReader 读取,但我遇到了一些问题。

当我再次阅读时,似乎数据的顺序不同,因此,我生成的体素块得到了错误的值。 据我了解,您必须按照编写数据的顺序读取数据,这是我应该做的。
我看过几个例子,但它们都让我想到了这个问题。 我不知道我做错了什么。

我在这里创建了一些测试代码,首先写入一个文件,然后立即读取它,然后检查加载的值是否与它保存的值匹配。 结果总是不匹配,总是停在同一个地方。

Block[] blocksToSave = chunk.blocks.GetBlocks();

using (BinaryWriter writer = new BinaryWriter(File.Open(Application.persistentDataPath + "/test.bin", FileMode.OpenOrCreate)))
{
    for (int i = 0; i < blocksToSave.Length; i++)
    {
        writer.Write(blocksToSave[i].id); // The ID is just a byte value.
    }
}

byte[] loadedBlocks = new byte[Chunk.CHUNK_SIZE * Chunk.CHUNK_SIZE * Chunk.CHUNK_SIZE]; // 16 * 16 * 16
using (BinaryReader reader = new BinaryReader(File.Open(Application.persistentDataPath + "/test.bin", FileMode.Open)))
{
    int pos = 0;
    int index = 0;
    int streamLength = (int)reader.BaseStream.Length;

    while (pos < streamLength)
    {
        byte id = reader.ReadByte();
        loadedBlocks[index] = id;
        pos += sizeof(int);
        index++;
    }
}

if (blocksToSave.Length != loadedBlocks.Length)
{
    Debug.LogError("Sizes does not match!");
    return;
}

for (int i = 0; i < blocksToSave.Length; i++)
{
    if (blocksToSave[i].id != loadedBlocks[i])
    {
        Debug.LogError("Expected " + blocksToSave[i].id + " but got " + loadedBlocks[i] + " at index " + i + ".");
        return;
    }
}

非常感谢任何帮助了解问题所在!
谢谢

pos += sizeof(int);

应该

pos += sizeof(byte);

暂无
暂无

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

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