Question

I have a file that containt struct like these :

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

For the word, I make sure I extend it to 30 bytes before writing it and the pos I write it as it is because I know that an int32 is 4 bytes.

Here is the code to write in the file :

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

The code compile and works well except for one thing : the int32 dosen't get written. If I check the file using notepad++ I see this where the int should be : SOH NULL NULL NULL I looked up SOH and it is supposed to be SOH (Start Of Heading):

This character is used to indicate the start of heading, which may contain address or routing information.

Can any of you see why my int32 is not writing?

code for you to try (the file will be saved in the bin debug folder of the project) :

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

        }
    }
}
Était-ce utile?

La solution

BinaryWriter writes its results encoded in a binary format. If you want to output text, use a StreamWriter. Text and bytes are not directly related. You cannot treat them as identical.

And please do not write chars by converting them to byte. If you don't know why this is not possible, please read up about character encodings. This is quite fundamental knowledge which every programmer needs to have.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top