Checking end of file on binary file

  • Thread starter Thread starter Chris
  • Start date Start date
C

Chris

Hi,

What is the most easy way to check on EOF while reading a
binary file with all integers ?

In lot of examples the read data are first stored in a
string, and afterwards the string is checked on *null*
value, but that does not work for binary files.

Like this ...
string buf;
while ( (buf = file.ReadString()) != null)
{
(...)
}

I need something like
int tim;
while ( (tim = file.ReadSingle()) != null)
{
(...)
}
but that does not work, as *tim* is an integer, and cant be
checked on *null*.

Is there a separate function (so, not getting any data) in
C# for merely checking the end-of-file condition ?

Thanks,
Chris.
 
Hi Chris,

You may be looking for BinaryReader.PeekChar()
It will return the integer value of the next character.
To force it to return the next byte instead of character
use the overloaded BinaryReader constructor specifying an
8-bit text encoding (for instance "ISO-8859-1").
 
Hi Chris
What is the most easy way to check on EOF while reading a
binary file with all integers ?

In case of binary file, the easiest way is to use *Stream*:

Stream stream;// initialize it e.g.:=new FileStream("c:\\temp.bin");
byte[] intBuffer=new byte[4];
int readCounter;

do {
readCounter=stream.Read(intBuffer
, 0
, 4);
if( readCounter==4 ) {
// set your int e.g.:
// myIntTable[index++]=BitConverter.ToInt32(intBuffer, 0);
}
}
while( readCounter==4 );
// i check here if buffer is filled with wanted
// number of bytes
In lot of examples the read data are first stored in a
string, and afterwards the string is checked on *null*
value, but that does not work for binary files.

Like this ...
string buf;
while ( (buf = file.ReadString()) != null)
{
(...)
}

I need something like
int tim;
while ( (tim = file.ReadSingle()) != null)
{
(...)
}
but that does not work, as *tim* is an integer, and cant be
checked on *null*.

Is there a separate function (so, not getting any data) in
C# for merely checking the end-of-file condition ?

Are you sure that you want to read file with integers
that were wrote in binary format?

HTH
Marcin
 
Back
Top