Binary file reading / writing

P

Patrick De Ridder

Writing and subsequently reading an int repeatedly
to and from a binary file I get an error when the int
vanlue becomes >= 128. Is there a possible
explanation for this?

Patrick.
 
P

Patrick De Ridder

Jan Tielens said:
Patrick

Could you post some code?
****************************************************************
Sure,
I have removed thr try / catches.
I have thrown out these methods in favour of calculating

recordNumber = (fileLength/recordSize);

but I would still like to know what I did wrong.

Patrick
****************************************************************
This works up until recordNumber = 128
and produces a bug if the recordNumber is bigger.

static public void putDataCounter(int recordNumber)
{
FileStream nrOut = new FileStream
(SomeFile,FileMode.Create,FileAccess.Write) ;
BinaryWriter outW = new BinaryWriter(nrOut);
outW.Write(recordNumber);
nrOut.Close();
outW.Close();
}

static public int getDataCounter()
{
FileStream nrIn = new FileStream
(SomeFile,FileMode.OpenOrCreate,FileAccess.Read) ;
BinaryReader inR new BinaryReader(nrIn);
int recordNumber = inR.ead();
nrIn.Close();
inR.Close();
return recordNumber;
}
****************************************************************
 
J

Jon Skeet [C# MVP]

Patrick De Ridder said:
This works up until recordNumber = 128
and produces a bug if the recordNumber is bigger.

static public void putDataCounter(int recordNumber)
{
FileStream nrOut = new FileStream
(SomeFile,FileMode.Create,FileAccess.Write) ;
BinaryWriter outW = new BinaryWriter(nrOut);
outW.Write(recordNumber);
nrOut.Close();
outW.Close();
}

static public int getDataCounter()
{
FileStream nrIn = new FileStream
(SomeFile,FileMode.OpenOrCreate,FileAccess.Read) ;
BinaryReader inR new BinaryReader(nrIn);
int recordNumber = inR.ead();
nrIn.Close();
inR.Close();
return recordNumber;
}

BinaryReader.Read() is to do with *characters* rather than bytes, and
BinaryWriter.Write(int) is writing a 4-byte integer to the stream.
Either use BinaryWriter.Write(byte) and BinaryReader.ReadByte(), or
BinaryWriter.Write(int) and BinaryReader.ReadInt32().
 
P

Patrick De Ridder

BinaryReader.Read() is to do with *characters* rather than bytes, and
BinaryWriter.Write(int) is writing a 4-byte integer to the stream.
Either use BinaryWriter.Write(byte) and BinaryReader.ReadByte(), or
BinaryWriter.Write(int) and BinaryReader.ReadInt32().

Think you.

Patrick.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top