Recent

Author Topic: Reading bytes from a specific address in a file  (Read 1685 times)

DumDum

  • New Member
  • *
  • Posts: 32
Reading bytes from a specific address in a file
« on: July 23, 2018, 12:14:49 pm »
Hi,

Wondering if there is a way to display specific bytes on the screen from a predesignated address in a binary file.

C

taazz

  • Hero Member
  • *****
  • Posts: 5368
Re: Reading bytes from a specific address in a file
« Reply #1 on: July 23, 2018, 12:38:55 pm »
In general, yes there are a couple of ways. Here is one example using streams.
Code: Pascal  [Select][+][-]
  1. function ReadBytes(const aFilename:string; aOffset, aCount:Int64):TByteArray;
  2. var
  3.   vFile:TFileStream;
  4. begin
  5.   vfile := TFileStream.Create(aFilename,fmOpenReadWrite or fmShareExclusive);
  6.   try
  7.     SetLength(Result,aCount);
  8.     vFile.Seek(aOffset, soFromBeginning);
  9.     vFile.Read(Result[0],aCount);
  10.   finally
  11.     vFile.Free;
  12.   end;
  13. end;
  14.  
here is the same procedure using binary files.
Code: Pascal  [Select][+][-]
  1. function ReadBytes(const aFilename:string; aOffset, aCount:Int64):TByteArray;
  2. var
  3.   vFile:File;
  4. begin
  5.   AssignFile(vFile, aFilename);
  6.   Reset(vFile, 1);
  7.   try
  8.     SetLength(Result, aCount);
  9.     Seek(vFile,aOffset);
  10.     BlockRead (vFile, Result[0], aCount);
  11.   finally
  12.     CloseFile(vFile);
  13.   end;
  14. end;
  15.  
Good judgement is the result of experience … Experience is the result of bad judgement.

OS : Windows 7 64 bit
Laz: Lazarus 1.4.4 FPC 2.6.4 i386-win32-win32/win64

Bart

  • Hero Member
  • *****
  • Posts: 5275
    • Bart en Mariska's Webstek
Re: Reading bytes from a specific address in a file
« Reply #2 on: July 23, 2018, 01:26:50 pm »
IIRC then blockread can only read chunks of size word (max 65536 bytes)?
At least that was the case in the old days.

Bart

taazz

  • Hero Member
  • *****
  • Posts: 5368
Re: Reading bytes from a specific address in a file
« Reply #3 on: July 23, 2018, 01:31:55 pm »
lazarus 1.4.4 has an overloaded version of blockread with int64 see attachement.
Good judgement is the result of experience … Experience is the result of bad judgement.

OS : Windows 7 64 bit
Laz: Lazarus 1.4.4 FPC 2.6.4 i386-win32-win32/win64

Thaddy

  • Hero Member
  • *****
  • Posts: 14204
  • Probably until I exterminate Putin.
Re: Reading bytes from a specific address in a file
« Reply #4 on: July 23, 2018, 01:54:54 pm »
And when you declare a File of record, you can read any - packed - record by its index.
Specialize a type, not a var.

 

TinyPortal © 2005-2018