Description |
Because binary streams can be written to in a direct manner, position in the stream may be changed at any time during the write process.
The new position is set to Offset bytes forward from the Origin.
The Origin may be one of the following values :
SeekOrigin.Begin | Byte 0 of the stream |
SeekOrigin.Current | The current stream position |
SeekOrigin.End | After the final byte of the stream |
|
| References | SeekOrigin
|
|
Microsoft MSDN Links |
System.IO
System.IO.BinaryWriter
|
|
|
Backtracking to overwrite a previoulsy written value |
program Project1;
{$APPTYPE CONSOLE}
uses
System.IO;
var
MyFileStream : System.IO.FileStream;
MyFileWriter : System.IO.BinaryWriter;
MyFileReader : System.IO.BinaryReader;
CharAsByte : Byte;
begin
// Create and open our binary file as a stream
MyFileStream := System.IO.File.Open('C:DelphiBasics.txt',
System.IO.FileMode.Create);
// Create a BinaryWriter to allow writing to this file
MyFileWriter := System.IO.BinaryWriter.Create(MyFileStream);
// Write to the file
MyFileWriter.Write('A');
MyFileWriter.Write('BCD'); // Chr(0x41)Chr(0x42)Chr(0x43)
MyFileWriter.Write(175);
// Position to the 3rd byte from the start and change it!
// Note : the 3rd byte is at offset 2 from the SeekOrigin
MyFileWriter.Seek(2, System.Io.SeekOrigin.Begin);
MyFileWriter.Write('Z'); // Was Chr(0x41), now Chr(0x5A)
// Close the writer and the stream
MyFileWriter.Close;
MyFileStream.Close;
// Reopen the stream for reading
MyFileStream := System.IO.File.Open('C:DelphiBasics.txt',
System.IO.FileMode.Open);
// Create a BinaryReader to allow the file to be read back
MyFileReader := System.IO.BinaryReader.Create(MyFileStream);
// Display the file contents
// Note : We must look for the 'EndOfStreamException'
// when using ReadByte to know when we are done
try
while 1 <> 0 do
begin
CharAsByte := MyFileReader.ReadByte;
Console.WriteLine('{0:X}', TObject(CharAsByte));
end;
except
On E : EndOfStreamException do
Console.WriteLine('End of file encountered');
end;
// Close the reader and the stream
MyFileReader.Close;
MyFileStream.Close;
Console.Readline;
end.
| Show full unit code | 41
3
5A
43
44
AF
End of file encountered
|
|
|
|