首页 文章

BinaryWriter.Write(Int32)已

提问于
浏览
1

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

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( Headers 开始):

此字符用于指示 Headers 的开头, Headers 可能包含地址或路由信息 .

谁能明白为什么我的int32不写?

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

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();

        }
    }
}

1 回答

  • 1

    BinaryWriter 将其结果写入二进制格式 . 如果要输出文本,请使用 StreamWriter . 文本和字节不直接相关 . 你不能把它们视为完全相同 .

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

相关问题