如何逐字节读取二进制文件?

威廉

我使用此代码每次准备一封信,但用于文本文件。

var
myFile : TextFile;
letter : char;
begin
  AssignFile(myFile, 'Test.txt');
  // Reopen the file for reading
  Reset(myFile);

  while not Eof(myFile) do begin
    // Proces one line at a time
    while not Eoln(myFile) do begin
      Read(myFile, letter);   // Read and display one letter at a time
    end;
    ReadLn(myFile, text);
  end;

  // Close the file for the last time
  CloseFile(myFile);

我可以用什么对二进制文件也逐字节做同样的事情?

心器

您没有提到您使用的是哪个版本的 Delphi。如果您使用的是相对较新的,则可以执行以下操作。如果您在 TBufferedFileStream 上遇到错误,请删除该行并使用 TFileStream 取消注释该行。

PROGRAM ByteReader;

{$APPTYPE CONSOLE}

USES SysUtils, Classes;

VAR
  S : TStream;
  O : Int64;
  B : BYTE;

BEGIN
  TRY
    // Open the file as a buffered file stream in Read/Only mode
    S:=TBufferedFileStream.Create(ParamStr(1),fmOpenRead);
    // If you get an error that TBufferedFileStream is unknown, use TFileStream instead.
    // It's compatible, but much slower
    // S:=TFileStream.Create(ParamStr(1),fmOpenRead);
    TRY
      // Reapeat for each byte (numbered 1 through the size (length) of the stream
      FOR O:=1 TO S.Size DO BEGIN
        // Read a single byte from the stream
        S.Read(B,SizeOf(BYTE));
        // Do whatever you want to do with it - here I am dumping it as a hex value
        WRITE(IntToHex(B))
      END
    FINALLY
      // Release the stream (and close the file)
      S.Free
    END
  EXCEPT
    ON E:Exception DO WRITELN(E.ClassName,': ',E.Message)
  END
END.

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章