Binary file reading / writing

  • Thread starter Thread starter Patrick De Ridder
  • Start date Start date
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.
 
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;
}
****************************************************************
 
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().
 
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.
 
Back
Top