Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/delphi/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/319.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Delphi读取非文本文件(二进制)_Delphi_File Io - Fatal编程技术网

Delphi读取非文本文件(二进制)

Delphi读取非文本文件(二进制),delphi,file-io,Delphi,File Io,如何在Delphi中以非文本模式打开二进制文件? 像C函数一样,有几个选项 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 St

如何在Delphi中以非文本模式打开二进制文件?
像C函数一样,有几个选项

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。使用读卡器

您可以将上述方法与
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
等从文件中读取。我真的不推荐这种方法。现代代码和库几乎总是喜欢流惯用法,通过自己这样做,您的代码将更容易与其他库兼容。

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

使用老派方法,如您指出的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;

读一读b“懒惰”?谷歌“德尔福读取二进制文件”现在我明白了其中的区别。File和TextFile类型的变量。谢谢大家。不要忘记
FileOpen()
FileRead()
FileClose()
函数,它们是
TFileStream
内部使用的.TFileCreate.Create?@eduado感谢愚蠢的打字错误。欢迎您编辑。