3

如何在 Delphi 中以非文本模式打开二进制文件?像 C 函数fopen(filename,"rb")

4

2 回答 2

15

有几个选项。

1.使用文件流

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.使用阅读器

您可以将上述方法与 a 结合起来,TBinaryReader使值的读取更简单:

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;

reader 类有很多函数可以读取其他数据类型。您可以使用二进制编写器朝相反的方向发展。

3. 旧式 Pascal I/O

您可以声明一个类型的变量File并使用AssignFile,BlockRead等从文件中读取。我真的不推荐这种方法。现代代码和库几乎总是更喜欢流习语,通过自己做同样的事情,您将使您的代码更容易适应其他库。

于 2012-11-27T11:31:25.000 回答
3

您有不同的选择,其中两个是:

使用老式方法,例如您指出的 C 函数:

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

使用更现代的方法基于文件创建 TFileStream:

var
  F: TFileStream;
begin
  F := TFileStream.Create('c:\some\path\to\file', fmOpenRead);
  try
    //work with the file
  finally
    F.Free;
  end;
于 2012-11-27T11:37:55.023 回答