我使用此代码每次只准备一个字母,但是用于文本文件。
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);
我可以用什么来逐字节地对二进制文件做同样的事情?
答案 0 :(得分:0)
您没有提到您使用的是哪个版本的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.