【问题标题】:BinaryWriter.Write(Int32)BinaryWriter.Write(Int32)
【发布时间】:2012-12-08 15:38:54
【问题描述】:

我有一个包含这样结构的文件:

public struct index
{
    public string word;         //30 bytes
    public int pos;             //4 bytes
};

对于这个词,我确保在写它之前将它扩展为 30 个字节,并且我按原样写它,因为我知道 int32 是 4 个字节。

这是要写入文件的代码:

for (i = 0; i < ind.word.Length; i++)
{
   bword[i] = (byte)idx_array[l].word[i];
}
for (; i < SIZE_WORD; i++) //30
{
   bword[i] = 0;
}
bw_idx.Write(bword, 0, SIZE_WORD);
bw_idx.Write(ind.pos);

代码编译并且运行良好,除了一件事:int32 没有被写入。如果我使用记事本++ 检查文件,我会看到 int 应该在哪里:SOH NULL NULL NULL 我查了 SOH,它应该是 SOH(标题开头):

这个字符用来表示标题的开始,它可以 包含地址或路由信息。

你们中的任何人都知道为什么我的 int32 没有写入吗?

代码供您尝试(文件将保存在项目的bin debug文件夹中):

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace test_write
{
    class Program
    {
        struct enreg
        {
            public string word;
            public int pos;
        }

        const int SIZE_WORD = 30; //30 bytes
        const int SIZE_POS = 4; //4 bytes

        static byte[] bword = new byte[SIZE_WORD];        
        static byte[] bpos = new byte[SIZE_POS];

        static void Main(string[] args)
        {
            enreg enr = new enreg();

            Console.Write("word : ");
            enr.word = Console.ReadLine();
            Console.Write("\anumber : ");
            enr.pos = int.Parse(Console.ReadLine());

            FileStream fs = File.Open("temp", FileMode.Create, FileAccess.ReadWrite);
            BinaryWriter bw = new BinaryWriter(fs);

            int i = 0;
            for (i = 0; i < enr.word.Length; i++)
            {
                bword[i] = (byte)enr.word[i];
            }
            for (; i < SIZE_WORD; i++)
            {
                bword[i] = 0;
            }
            bpos = BitConverter.GetBytes(enr.pos);

            bw.Write(bword, 0, SIZE_WORD);
            bw.Write(bpos, 0, SIZE_POS);

            fs.Close();

        }
    }
}

【问题讨论】:

  • 我猜你最好使用十六进制编辑器而不是 Notepad++。 Frhed 是一个不错的开源软件。还要检查您是否已正确关闭(或刷新)文件。
  • 另外,我没有看到FileStream.Write(Int32)。你的意思是BinaryWriter.Write(Int32)
  • 它关闭得很好,即使我冲洗它也不起作用
  • 或许您应该隔离问题并提供一个简短的、自包含的代码让我们重现问题
  • 正如我所说,使用十六进制编辑器而不是 Notepad++。

标签: c# file int32 binarywriter


【解决方案1】:

BinaryWriter二进制 格式写入其结果。如果要输出文本,请使用StreamWriter。文本和字节没有直接关系。您不能将它们视为相同。

请不要通过将字符转换为字节来写入字符。如果您不知道为什么这是不可能的,请阅读有关字符编码的信息。这是每个程序员都需要具备的基础知识。

【讨论】:

  • 但是是的,他有点老派 ;)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-11-14
  • 1970-01-01
  • 2019-03-15
  • 1970-01-01
  • 2016-02-28
  • 2013-09-26
  • 2011-03-01
相关资源
最近更新 更多