Delphi reading non-text file (binary)

delphi, file-io

Solution

There are a few options.

1. Use a file stream

var
  Stream: TFileStream;
  Value: Integer;
....
Stream := TFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite);
try
  Stream.ReadBuffer(Value, SizeOf(Value));//read a 4 byte integer
finally
  Stream.Free;
end;

2. Use a reader

You would combine the above approach with a `TBinaryReader` to make the reading of the values simpler:

var
  Stream: TFileStream;
  Reader: TBinaryReader;
  Value: Integer;
....
Stream := TFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite);
try
  Reader := TBinaryReader.Create(Stream);
  try
    Value := Reader.ReadInteger;
  finally
    Reader.Free;
  end;
finally
  Stream.Free;
end;

The reader class has lots of functions to read other data types. And you can go in the opposite direction with a binary writer.

3. Old style Pascal I/O

You can declare a variable of type `File` and use `AssignFile`, `BlockRead`, etc. to read from the file. I really don't recommend this approach. Modern code and libraries almost invariably prefer the stream idiom and by doing the same yourself you'll make your code easier to fit with other libraries.

Problem

how in Delphi could I open binary file in non-text mode? Like C function `fopen(filename,"rb")`

Original source