how in Delphi could I open binary file in non-text mode?
Like C function fopen(filename,"rb")
2 Answers
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.
4 Comments
FileOpen(), FileRead(), and FileClose() functions, which are what TFileStream uses internally.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;