3

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

0

2 Answers 2

15

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Now I see where is the difference. Variable of type File and TextFile. Thanks you all.
Don't forget the FileOpen(), FileRead(), and FileClose() functions, which are what TFileStream uses internally.
TFileCreate.Create ?
@eduado thanks silly typo. You would have been welcome to edit.
3

You have different options, two of them are:

Use the old school approach, like the C function you pointed out:

var
  F: File;
begin
  AssignFile(F, 'c:\some\path\to\file');
  ReSet(F);
  try
    //work with the file
  finally
    CloseFile(F);
  end
end;

Use a more modern approach to create a TFileStream based on the file:

var
  F: TFileStream;
begin
  F := TFileStream.Create('c:\some\path\to\file', fmOpenRead);
  try
    //work with the file
  finally
    F.Free;
  end;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.