Reading with Cache!

Unit ZVFiles;

{**************************************************************
* ZAK'S VIRTUAL FILES *
* unit for reading file with cache. More speed on reading!!! *
**************************************************************}

Interface

Var
VEOF : Boolean;
Back : Boolean;

Procedure OpenFile(Path : String);
Function ReadByte : Byte;
Function ReadWord : Word;
Procedure Backward;
Procedure CloseFile;

Implementation

Var
F : File;
Data : Pointer;
DataSize, DataPos, DataEOF : Word;
OldByte : Byte;
OldWord : Word;

Procedure OpenFile;
Var
fs : LongInt;
Begin
VEOF := False;
DataPos := 0;
DataEOF := 65535;
Assign(f, Path);
Reset(f, 1);
fs := FileSize(f);
Close(f);
If MaxAvail > 5120 Then
DataSize := 5120
Else
DataSize := MaxAvail;
If fs <= DataSize Then DataSize := fs;
GetMem(Data, DataSize);
Reset(f, DataSize);
BlockRead(f, Data^, 1);
If EOF(f) Then DataEOF := DataSize
End;

Procedure CloseFile;
Begin
Close(f);
FreeMem(Data, DataSize)
End;

Procedure ReRead;
Var
nr : Word;
Begin
DataPos := 0;
BlockRead(f, Data^, 1, nr);
If EOF(f) Then DataEOF := DataSize
End;

Function ReadByte;
Begin
If Back Then
Begin
ReadByte := OldByte;
Back := False;
Exit
End;
Back := False;
OldByte := Mem[Seg(Data^):Ofs(Data^)+DataPos];
ReadByte := OldByte;
Inc(DataPos);
If DataPos = DataEOF Then
Begin
VEOF := True;
Dec(DataPos)
End;
If (DataPos >= DataSize) And (VEOF = False) Then ReRead;
End;

Function ReadWord;
Var
b1, b2 : Byte;
Begin
If Back Then
Begin
ReadWord := OldWord;
Back := False;
Exit
End;
Back := False;
b1 := ReadByte;
b2 := ReadByte;
OldWord := b2 * 256 + b1;
ReadWord := OldWord
End;

Procedure Backward;
Begin
Back := True
End;

End.

--------------
Example:

program showfile;
uses ZVFiles, CRT;

var
c : Char;
s : String;
begin
Write('File name: ');
ReadLn(s);
OpenFile(s);
ClrScr;
While Not VEOF Do
begin
c := Chr(ReadByte);
Write(c);
end;

Closefile
end.



This Unit is much much faster than reading a bytes/word based file directly.

Enjoy!

Sign In or Register to comment.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories