Masoud AMR
Masoud AMR

Reputation: 134

Reading a record from file

I am trying to read a Unicode record from binary file and stored in object, but the last byte of the buffer does not save, why?

b = new byte[55];

file.read(b, 0, b.length)

set(b);

    private static int sizePtr = 4;
    private static int sizeBf = 50;
    private byte deleteTag ;                    
    private byte []buf = new byte[sizeBf];    
    private byte []pointer = new byte[sizePtr];

    public void set( byte[] b) 
    {
        deleteTag = b[0];      
        Int32 l;

        for (l = 0; l < sizeOfBuffer(); l++) 
            buf[l] = b[l+1];

        for (int i = 0; i < sizePtr; i++, l++)
            pointer[i] = b[l];
    }

Upvotes: 0

Views: 135

Answers (2)

T_D
T_D

Reputation: 1728

You did not specify your specific use case but I would say what you need is the BinaryReader class. It is useful if you want to read a binary file with data that you know the structure of. In your case it could be something like that:

var br = new BinaryReader(File.OpenRead(filePath));

private static int sizePtr = 4;
private static int sizeBf = 50;
private byte deleteTag ;                    
private byte []buf = new byte[sizeBf];    
private byte []pointer = new byte[sizePtr];

//read deleteTag
deleteTag = br.ReadByte();
buf = br.ReadBytes(sizeBf);
pointer = br.ReadBytes(sizePtr);

If your pointer is a 4byte integer value you could also do this instead:

pointer = br.ReadUInt32();

So if your binary file is quite complex the binaryReader will be very helpful.

Upvotes: 3

S_F
S_F

Reputation: 887

The last execution of the first loop has l=49 (assuming sizeofBuffer() simply returns sizeBf), which makes it

buf[49] = b[50]

After that the first execution of the second loop has l=50 and that makes your code do

pointer[0] = b[50]

Then the last execution of that loop will be

pointer[3] = b[53]

Given that, you are losing the last byte. I'd recommend changing the second loop to

for (int i = 0; i < sizePtr; i++, l++)
    pointer[i] = b[l+1];

unless there's more processing after that which you haven't shown in your code.

Upvotes: 1

Related Questions