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