1 | // TTextFileStream class by Chronos 12.9.2005
|
---|
2 | // Homepage: http://jirihajda.zdechov.net/
|
---|
3 |
|
---|
4 | unit UTextFileStream;
|
---|
5 |
|
---|
6 | {$mode Delphi}{$H+}
|
---|
7 |
|
---|
8 | interface
|
---|
9 |
|
---|
10 | uses Classes, SysUtils;
|
---|
11 |
|
---|
12 | type
|
---|
13 |
|
---|
14 | TTextFileStream = class(TFileStream)
|
---|
15 | private
|
---|
16 | FBuffer: string;
|
---|
17 | protected
|
---|
18 |
|
---|
19 | public
|
---|
20 | function Eof: Boolean;
|
---|
21 | procedure WriteLn(Text: string);
|
---|
22 | function ReadLn: string;
|
---|
23 | function Seek(const Offset: Int64; Origin: TSeekOrigin): Int64; override;
|
---|
24 | function RowsCount: Integer;
|
---|
25 | end;
|
---|
26 |
|
---|
27 | implementation
|
---|
28 |
|
---|
29 | { TTextFileStream }
|
---|
30 |
|
---|
31 | function TTextFileStream.Eof: Boolean;
|
---|
32 | begin
|
---|
33 | Eof := ((Position - Length(FBuffer)) = Size);
|
---|
34 | end;
|
---|
35 |
|
---|
36 | function TTextFileStream.ReadLn: string;
|
---|
37 | const
|
---|
38 | BufferLength = 10000;
|
---|
39 | var
|
---|
40 | NewBuffer: string;
|
---|
41 | Readed: Integer;
|
---|
42 | begin
|
---|
43 | Readed := 1;
|
---|
44 | while (Pos(#13, FBuffer) = 0) and (Readed > 0) do begin
|
---|
45 | SetLength(NewBuffer, BufferLength + 2);
|
---|
46 | Readed := Read(NewBuffer[1], BufferLength);
|
---|
47 | SetLength(NewBuffer, Readed);
|
---|
48 | FBuffer := FBuffer + NewBuffer;
|
---|
49 | end;
|
---|
50 | if Pos(#13, FBuffer) > 0 then begin
|
---|
51 | Result := Copy(FBuffer, 1, Pos(#13, FBuffer) - 1);
|
---|
52 | Delete(FBuffer, 1, Pos(#13, FBuffer) + 1);
|
---|
53 | end else begin
|
---|
54 | Result := FBuffer;
|
---|
55 | FBuffer := '';
|
---|
56 | end;
|
---|
57 | end;
|
---|
58 |
|
---|
59 | function TTextFileStream.RowsCount: Integer;
|
---|
60 | begin
|
---|
61 | Result := 1;
|
---|
62 | FBuffer := '';
|
---|
63 | Seek(0, soBeginning);
|
---|
64 | while not Eof do begin
|
---|
65 | ReadLn;
|
---|
66 | Inc(Result);
|
---|
67 | end;
|
---|
68 | Seek(0, soBeginning);
|
---|
69 | end;
|
---|
70 |
|
---|
71 | function TTextFileStream.Seek(const Offset: Int64;
|
---|
72 | Origin: TSeekOrigin): Int64;
|
---|
73 | begin
|
---|
74 | if Origin = soCurrent then
|
---|
75 | Result := inherited Seek(Offset - Length(FBuffer), Origin)
|
---|
76 | else Result := inherited Seek(Offset, Origin);
|
---|
77 | FBuffer := '';
|
---|
78 | end;
|
---|
79 |
|
---|
80 | procedure TTextFileStream.WriteLn(Text: string);
|
---|
81 | const
|
---|
82 | NewLine = #13#10;
|
---|
83 | begin
|
---|
84 | Seek(0, soCurrent);
|
---|
85 | Write(Text[1], Length(Text));
|
---|
86 | Write(NewLine, 2);
|
---|
87 | end;
|
---|
88 |
|
---|
89 | end.
|
---|