BinaryWriter.Write(Int32)已

时间:2012-12-08 15:38:55

标签: c# file int32 binarywriter

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

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不会被写入。如果我使用notepad ++检查文件,我会看到int应该是:SOH NULL NULL NULL 我抬头看了SOH,它应该是SOH(标题的开始):

  

此字符用于表示标题的开始,可以是   包含地址或路由信息。

你们有没有人能够理解为什么我的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 个答案:

答案 0 :(得分:1)

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

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

相关问题