Description |
The File keyword is used to define a variable as a binary file, normally as written to and read from a storage device.
Version 1
Gives a base untyped file. Such a file can only be read from and written to using BlockRead and BlockWrite. The basic data type is a byte.
AssignFile must be used to get a file handle.
Reset or ReWrite must then be used to open the file for read and/or write access. These specify the number of bytes that comprise one 'record' as seen by the BlockRead and BlockWrite routines.
Version 2
Defines the file with a base data type. For example, a simple type such as a char or a complex type such as a Record.
AssignFile must be used to get a file handle.
Reset or ReWrite must then be used to open the file for read and/or write access. Read and Write must be used to access the file.
In all cases, the type must be of fixed size, and access to the file must be in units of that type.
|
|
Notes |
When using Records, make sure that they are Packed to prevent alignment problems.
|
|
Related commands |
Append |
|
Open a text file to allow appending of text to the end |
AssignFile |
|
Assigns a file handle to a binary or text file |
CloseFile |
|
Closes an open file |
Reset |
|
Open a text file for reading, or binary file for read/write |
ReWrite |
|
Open a text or binary file for write access |
TextFile |
|
Declares a file type for storing lines of text |
|
|
|
Example code : Read and write access to an untyped binary file |
var
myFile : File;
byteArray : array[1..8] of byte;
oneByte : byte;
i, count : Integer;
begin // Try to open the Test.byt file for writing to
AssignFile(myFile, 'Test.byt'); ReWrite(myFile, 4); // Define a single 'record' as 4 bytes
// Fill out the data array
for i := 1 to 8 do
byteArray[i] := i;
// Write the data array to the file BlockWrite(myFile, byteArray, 2); // Write 2 'records' of 4 bytes
// Close the file
CloseFile(myFile);
// Reopen the file for reading Reset(myFile, 1); // Now we define one record as 1 byte
// Display the file contents
while not Eof(myFile) do
begin BlockRead(myFile, oneByte, 1); // Read and display one byte at a time
ShowMessage(IntToStr(oneByte));
end;
// Close the file for the last time
CloseFile(myFile);
end;
|
Show full unit code |
1
2
3
4
5
6
7
8
|
|
Example code : Writing to a typed binary file |
var
myWord, myWord1, myWord2 : Word;
myFile : File of Word;
begin // Try to open the Test.bin binary file for writing to
AssignFile(myFile, 'Test.cus');
ReWrite(myFile);
// Write a couple of lines of Word data to the file
myWord1 := 234;
myWord2 := 567;
Write(myFile, myWord1, myWord2);
// Close the file
CloseFile(myFile);
// Reopen the file in read only mode
Reset(myFile);
// Display the file contents
while not Eof(myFile) do
begin
Read(myFile, myWord);
ShowMessage(IntToStr(myWord));
end;
// Close the file for the last time
CloseFile(myFile);
end;
|
Show full unit code |
234
567
|
|