DelphiBasics
Seek
Procedure
Move the pointer in a binary file to a new record position System unit
 procedure Seek(var FileHandle File; RecordNumber LongInt);
Description
The Seek procedure moves the current record position in an open binary file given by FileHandle to a new position RecordNumber.
 
The file must have been assigned with AssignFile and opened with Reset or ReWrite.
 
For untyped files, the record size is set with the Reset or ReWrite routine used.
 
For typed files, the record size is SizeOf the file type.
 
The first record in a file is record 0.
Notes
Use SeekEoln or SeekEof to move the file pointer on a text file.
Related commands
EofReturns true if a file opened with Reset is at the end
EolnReturns true if the current text file is pointing at a line end
FileDefines a typed or untyped file
FilePosGives the file position in a binary or text file
SeekEolnSkip to the end of the current line or file
 Download this web site as a Windows program.




 
Example code : Repositioning in a Word type file
var
  myWord, myWord1, myWord2, myWord3, myWord4 : Word;
  myFile : File of Word;

begin
  // Try to open the Test.cus binary file in write only mode
  AssignFile(myFile, 'Test.cus');
  ReWrite(myFile);

  // Write a few lines of Word data to the file
  myWord1 := 12;
  myWord2 := 34;
  myWord3 := 56;
  myWord4 := 78;
  Write(myFile, myWord1, myWord2, myWord3, myWord4);

  // Close the file
  CloseFile(myFile);

  // Reopen the file for read only purposes
  FileMode := fmOpenRead;
  Reset(myFile);

  // Seek (move) to the start of the 3rd record
  Seek(myFile, 2);    // Records start from 0

  // Show this record
  Read(myFile, myWord);
  ShowMessage('Record 3 = '+IntToStr(myWord));

  // Close the file
  CloseFile(myFile);
end;
Show full unit code
  Record 3 = 56
 
Delphi Programming © Neil Moffatt . All rights reserved.  |  Home Page