forked from exilon/QuickLib
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Quick.Files.pas
1157 lines (1024 loc) · 31.4 KB
/
Quick.Files.pas
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
{ ***************************************************************************
Copyright (c) 2016-2018 Kike Pérez
Unit : Quick.Files
Description : Files functions
Author : Kike Pérez
Version : 1.2
Created : 09/03/2018
Modified : 29/05/2018
This file is part of QuickLib: https://github.com/exilon/QuickLib
***************************************************************************
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*************************************************************************** }
unit Quick.Files;
{$i QuickLib.inc}
interface
uses
Classes,
SysUtils,
{$IFDEF MSWINDOWS}
Windows,
{$ENDIF}
{$IFDEF FPC}
strutils,
{$IFDEF LINUX}
baseunix,
{$ENDIF}
{$ENDIF}
DateUtils;
{$IFDEF FPC}
resourcestring
SPathTooLong = 'The specified path is too long';
SPathNotFound = 'The specified path was not found';
SPathFormatNotSupported = 'The path format is not supported';
SDirectoryNotEmpty = 'The specified directory is not empty';
SDirectoryAlreadyExists = 'The specified directory already exists';
SDirectoryInvalid = 'The specified directory name is invalid';
SSourceDirIsDestDir = 'The source directory is the same as the destination directory';
SSourceFileIsDestFile = 'The source file is the same as the destination file';
SPathToFileNeeded = 'The path must specify a file';
SSameRootDrive = 'The source and destination paths must contain the same root drive';
SDriveNotFound = 'The drive cannot be found';
SFileNotFound = 'The specified file was not found';
SFileAlreadyExists = 'The specified file already exists';
SInvalidCharsInPath = 'Invalid characters in path';
SInvalidCharsInFileName = 'Invalid characters in file name';
{$ENDIF}
type
{$IFNDEF FPC}
TTextFileOperation = (tfOpenRead,tfOpenOverwrite,tfOpenAppend);
TTextStreamFile = class
private
fReadStream : TStreamReader;
fWriteStream : TStreamWriter;
function GetEOF : Boolean;
public
constructor Create(const aFileName : string; aOpenMode : TTextFileOperation);
destructor Destroy; override;
function ReadLn: string; overload;
function ReadLn(out Data: string): Boolean; overload;
procedure WriteLn (const Data : string);
procedure Close;
property EOF: Boolean read GetEOF;
end;
{$ELSE}
{$IFDEF LINUX}
TFILETIME = LongInt;
{$ENDIF}
{$ENDIF}
{$IFDEF FPC}
EStreamError = class(Exception);
EFileStreamError = class(EStreamError)
constructor Create(ResStringRec: PResStringRec; const FileName: string);
end;
TPathPrefixType = (pptNoPrefix, pptExtended, pptExtendedUNC);
TPath = class
private
const
FCCurrentDir: string = '.';
FCParentDir: string = '..';
FCExtendedPrefix: string = '\\?\';
FCExtendedUNCPrefix: string = '\\?\UNC\';
class procedure CheckPathLength(const Path: string; const MaxLength: Integer);
public
class function GetFileNameWithoutExtension(const FileName : string) : string;
class function GetDirectoryName(const FileName : string) : string;
class function GetExtension(const Path : string) : string;
class function ChangeExtension(const Path, NewExtension : string) : string;
end;
TDirectory = class
public
class function Exists(const Path: string; FollowLink: Boolean = True): Boolean;
end;
TFile = class
public
class function Exists(const Path : string) : Boolean;
class function IsInUse(const Path : string) : Boolean;
class function GetSize(const Path : string) : Int64;
class function Create(const Path: string; const BufferSize: Integer): TFileStream; overload;
class function Create(const Path: string): TFileStream; overload;
class function GetExtension(const Path : string) : string;
class function GetCreationTime(const Path : string): TDateTime;
class function GetLastAccessTime(const Path : string): TDateTime;
class function GetLastWriteTime(const Path : string): TDateTime;
class procedure SetCreationTime(const Path: string; const CreationTime: TDateTime);
class procedure SetLastAccessTime(const Path: string; const LastAccessTime: TDateTime);
class procedure SetLastWriteTime(const Path: string; const LastWriteTime: TDateTime);
class function IsReadOnly(const Path : string) : Boolean;
class function Delete(const Path : string) : Boolean;
class function Move(const SourceFileName, DestFileName: string) : Boolean;
end;
TTextWriter = class
public
procedure Close; virtual; abstract;
procedure Flush; virtual; abstract;
procedure Write(Value: Boolean); overload; virtual; abstract;
procedure Write(Value: Char); overload; virtual; abstract;
procedure Write(Value: Double); overload; virtual; abstract;
procedure Write(Value: Integer); overload; virtual; abstract;
procedure Write(Value: Int64); overload; virtual; abstract;
procedure Write(Value: TObject); overload; virtual; abstract;
procedure Write(Value: Single); overload; virtual; abstract;
procedure Write(const Value: string); overload; virtual; abstract;
procedure Write(const aFormat: string; Args: array of const); overload; virtual; abstract;
procedure WriteLine; overload; virtual; abstract;
procedure WriteLine(Value: Boolean); overload; virtual; abstract;
procedure WriteLine(Value: Char); overload; virtual; abstract;
procedure WriteLine(Value: Double); overload; virtual; abstract;
procedure WriteLine(Value: Integer); overload; virtual; abstract;
procedure WriteLine(Value: Int64); overload; virtual; abstract;
procedure WriteLine(Value: TObject); overload; virtual; abstract;
procedure WriteLine(Value: Single); overload; virtual; abstract;
procedure WriteLine(const Value: string); overload; virtual; abstract;
procedure WriteLine(const aFormat: string; Args: array of const); overload; virtual; abstract;
end;
TStreamWriter = class(TTextWriter)
private
FStream: TStream;
FEncoding: TEncoding;
FNewLine: string;
FAutoFlush: Boolean;
FOwnsStream: Boolean;
FBufferIndex: Integer;
FBuffer: TBytes;
procedure WriteBytes(Bytes: TBytes);
public
constructor Create(Stream: TStream); overload;
constructor Create(Stream: TStream; Encoding: TEncoding; BufferSize: Integer = 4096); overload;
constructor Create(const Filename: string; Append: Boolean = False); overload;
constructor Create(const Filename: string; Append: Boolean; Encoding: TEncoding; BufferSize: Integer = 4096); overload;
destructor Destroy; override;
procedure Close; override;
procedure Flush; override;
procedure OwnStream; inline;
procedure Write(Value: Boolean); override;
procedure Write(Value: Char); override;
procedure Write(Value: Double); override;
procedure Write(Value: Integer); override;
procedure Write(Value: Int64); override;
procedure Write(Value: TObject); override;
procedure Write(Value: Single); override;
procedure Write(const Value: string); override;
procedure Write(const aFormat: string; Args: array of const); override;
procedure WriteLine; override;
procedure WriteLine(Value: Boolean); override;
procedure WriteLine(Value: Char); override;
procedure WriteLine(Value: Double); override;
procedure WriteLine(Value: Integer); override;
procedure WriteLine(Value: Int64); override;
procedure WriteLine(Value: TObject); override;
procedure WriteLine(Value: Single); override;
procedure WriteLine(const Value: string); override;
procedure WriteLine(const aFormat: string; Args: array of const); override;
property AutoFlush: Boolean read FAutoFlush write FAutoFlush;
property NewLine: string read FNewLine write FNewLine;
property Encoding: TEncoding read FEncoding;
property BaseStream: TStream read FStream;
end;
{$ENDIF FPC}
function CreateDummyFile(const aFilename : string; const aSize : Int64) : Boolean;
procedure SplitFile(const aFileName : string; aSplitByteSize : Int64);
procedure MergeFiles(const aFirstSplitFileName, aOutFileName : string); overload;
procedure MergeFiles(aFilenames : array of string; const aOutFileName : string); overload;
function IsFileInUse(const aFileName : string) : Boolean;
procedure FileReplaceText(const aFileName, aSearchText, AReplaceText : string);
function FileSearchText(const aFileName, SearchText: string; caseSensitive : Boolean): Longint;
function GetCreationTime(const aFilename : string): TDateTime;
function GetLastAccessTime(const aFileName: string): TDateTime;
function GetLastWriteTime(const aFileName : string): TDateTime;
{$IFDEF FPC}
function FindDelimiter(const Delimiters, S: string; StartIdx: Integer = 1): Integer;
{$ENDIF}
function ConvertDateTimeToFileTime(const DateTime: TDateTime; const UseLocalTimeZone: Boolean): TFileTime;
procedure SetDateTimeInfo(const Path: string; const CreationTime, LastAccessTime, LastWriteTime: PDateTime; const UseLocalTimeZone: Boolean);
implementation
{ TTextStreamFile }
{$IFNDEF FPC}
constructor TTextStreamFile.Create(const aFileName : string; aOpenMode : TTextFileOperation);
var
Append : Boolean;
begin
if aOpenMode = tfOpenRead then fReadStream := TStreamReader.Create(aFileName,True)
else
begin
if aOpenMode = tfOpenAppend then Append := True
else Append := False;
fWriteStream := TStreamWriter.Create(aFileName,Append);
end;
end;
destructor TTextStreamFile.Destroy;
begin
if Assigned(fReadStream) then fReadStream.Free;
if Assigned(fWriteStream) then fWriteStream.Free;
inherited Destroy;
end;
function TTextStreamFile.ReadLn(out Data: string): Boolean;
begin
Data := fReadStream.ReadLine;
Result := Data <> '';
end;
function TTextStreamFile.ReadLn: string;
begin
Result := fReadStream.ReadLine;
end;
procedure TTextStreamFile.WriteLn (const Data : string);
begin
fWriteStream.WriteLine(Data);
end;
function TTextStreamFile.GetEOF : Boolean;
begin
Result := fReadStream.EndOfStream;
end;
procedure TTextStreamFile.Close;
begin
if Assigned(fReadStream) then fReadStream.Close;
if Assigned(fWriteStream) then fWriteStream.Close;
end;
{$ENDIF NFPC}
{$IFDEF FPC}
{ EFileStreamError }
constructor EFileStreamError.Create(ResStringRec: PResStringRec;
const FileName: string);
begin
{$IFNDEF LINUX}
inherited CreateResFmt(ResStringRec, [ExpandFileName(FileName), SysErrorMessage(GetLastError)]);
{$ELSE}
inherited CreateResFmt(ResStringRec, [ExpandFileName(FileName), SysErrorMessage(errno)]);
{$ENDIF}
end;
{ TPath }
class function TPath.GetFileNameWithoutExtension(const FileName: String): String;
var
fname : string;
begin
fname := ExtractFileName(FileName);
Result := Copy(fname, 1, Length(fname) - Length(ExtractFileExt(fname)));
end;
class function TPath.ChangeExtension(const Path, NewExtension : string) : string;
var
dot : string;
begin
if NewExtension.Contains('.') then dot := ''
else dot := '.';
Result := TPath.GetFileNameWithoutExtension(Path) + dot + NewExtension;
end;
class function TPath.GetDirectoryName(const FileName : string) : string;
begin
Result := ExtractFileDir(Filename);
end;
class procedure TPath.CheckPathLength(const Path: string; const MaxLength: Integer);
begin
{$IFDEF MSWINDOWS}
if (Length(Path) >= MaxLength) then
{$ENDIF MSWINDOWS}
{$IFDEF POSIX}
if (Length(UTF8Encode(Path)) >= MaxLength) then
{$ENDIF POSIX}
raise EPathTooLongException.CreateRes(@SPathTooLong);
end;
class function TPath.GetExtension(const Path : string) : string;
begin
Result := ExtractFileExt(Path);
end;
{ TDirectory }
class function TDirectory.Exists(const Path: string; FollowLink: Boolean = True): Boolean;
begin
Result := DirectoryExists(Path);
end;
{ TFile }
class function TFile.Exists(const Path : string) : Boolean;
begin
Result := FileExists(Path);
end;
class procedure TFile.SetCreationTime(const Path: string; const CreationTime: TDateTime);
begin
SetDateTimeInfo(Path,@CreationTime,nil,nil,True);
end;
class procedure TFile.SetLastAccessTime(const Path: string; const LastAccessTime: TDateTime);
begin
SetDateTimeInfo(Path,nil,@LastAccessTime,nil,True);
end;
class procedure TFile.SetLastWriteTime(const Path: string; const LastWriteTime: TDateTime);
begin
SetDateTimeInfo(Path,nil,nil,@LastWriteTime,True);
end;
class function TFile.IsReadOnly(const Path : string) : Boolean;
begin
Result := FileIsReadOnly(Path);
end;
class function TFile.Delete(const Path : string) : Boolean;
begin
Result := DeleteFile(PChar(Path));
end;
class function TFile.Move(const SourceFileName, DestFileName: string) : Boolean;
begin
{$IFNDEF LINUX}
Result := MoveFile(PChar(SourceFileName),PChar(DestFileName));
{$ELSE}
Result := RenameFile(PChar(SourceFileName),PChar(DestFileName));
{$ENDIF}
end;
class function TFile.IsInUse(const Path : string) : Boolean;
begin
Result := IsFileInUse(Path);
end;
class function TFile.GetSize(const Path : string) : Int64;
var
f : File of Byte;
begin
Assign(f,Path);
try
Reset (f);
Result := FileSize(f);
finally
CloseFile(f);
end;
end;
class function TFile.GetExtension(const Path : string) : string;
begin
Result := ExtractFileExt(Path);
end;
class function TFile.GetCreationTime(const Path : string) : TDateTime;
begin
Result := Quick.Files.GetCreationTime(Path);
end;
class function TFile.GetLastAccessTime(const Path : string) : TDateTime;
begin
Result := Quick.Files.GetLastAccessTime(Path);
end;
class function TFile.GetLastWriteTime(const Path : string) : TDateTime;
begin
Result := Quick.Files.GetLastWriteTime(Path);
end;
class function TFile.Create(const Path: string; const BufferSize: Integer): TFileStream;
begin
try
Result := TFileStream.Create(Path,fmCreate);
except
on E: EFileStreamError do
raise EInOutError.Create(E.Message);
end;
end;
class function TFile.Create(const Path: string): TFileStream;
begin
Result := Create(Path, 0);
end;
{ TStreamWriter }
procedure TStreamWriter.Close;
begin
Flush;
if FOwnsStream then
FreeAndNil(FStream);
end;
constructor TStreamWriter.Create(Stream: TStream);
begin
inherited Create;
FOwnsStream := False;
FStream := Stream;
FEncoding := TEncoding.UTF8;
SetLength(FBuffer, 1024);
FBufferIndex := 0;
FNewLine := sLineBreak;
FAutoFlush := True;
end;
constructor TStreamWriter.Create(Stream: TStream; Encoding: TEncoding; BufferSize: Integer);
begin
inherited Create;
FOwnsStream := False;
FStream := Stream;
FEncoding := Encoding;
if BufferSize >= 128 then
SetLength(FBuffer, BufferSize)
else
SetLength(FBuffer, 128);
FBufferIndex := 0;
FNewLine := sLineBreak;
FAutoFlush := True;
if Stream.Position = 0 then
WriteBytes(FEncoding.GetPreamble);
end;
constructor TStreamWriter.Create(const Filename: string; Append: Boolean);
begin
if (not FileExists(Filename)) or (not Append) then
FStream := TFileStream.Create(Filename, fmCreate)
else
begin
FStream := TFileStream.Create(Filename, fmOpenWrite);
FStream.Seek(0, soEnd);
end;
Create(FStream);
FOwnsStream := True;
end;
constructor TStreamWriter.Create(const Filename: string; Append: Boolean;
Encoding: TEncoding; BufferSize: Integer);
begin
if (not FileExists(Filename)) or (not Append) then
FStream := TFileStream.Create(Filename, fmCreate)
else
begin
FStream := TFileStream.Create(Filename, fmOpenWrite);
FStream.Seek(0, soEnd);
end;
Create(FStream, Encoding, BufferSize);
FOwnsStream := True;
end;
destructor TStreamWriter.Destroy;
begin
Close;
SetLength(FBuffer, 0);
inherited;
end;
procedure TStreamWriter.Flush;
begin
if FBufferIndex = 0 then
Exit;
if FStream = nil then
Exit;
FStream.Write(FBuffer[0], FBufferIndex);
FBufferIndex := 0;
end;
procedure TStreamWriter.OwnStream;
begin
FOwnsStream := True;
end;
procedure TStreamWriter.Write(const Value: string);
begin
WriteBytes(FEncoding.GetBytes(Value));
end;
procedure TStreamWriter.WriteBytes(Bytes: TBytes);
var
ByteIndex: Integer;
WriteLen: Integer;
begin
ByteIndex := 0;
while ByteIndex < Length(Bytes) do
begin
WriteLen := Length(Bytes) - ByteIndex;
if WriteLen > Length(FBuffer) - FBufferIndex then
WriteLen := Length(FBuffer) - FBufferIndex;
Move(Bytes[ByteIndex], FBuffer[FBufferIndex], WriteLen);
Inc(FBufferIndex, WriteLen);
Inc(ByteIndex, WriteLen);
if FBufferIndex >= Length(FBuffer) then
Flush;
end;
if FAutoFlush then
Flush;
end;
procedure TStreamWriter.Write(const aFormat: string; Args: array of const);
begin
WriteBytes(FEncoding.GetBytes(Format(aFormat, Args)));
end;
procedure TStreamWriter.Write(Value: Single);
begin
WriteBytes(FEncoding.GetBytes(FloatToStr(Value)));
end;
procedure TStreamWriter.Write(Value: Double);
begin
WriteBytes(FEncoding.GetBytes(FloatToStr(Value)));
end;
procedure TStreamWriter.Write(Value: Integer);
begin
WriteBytes(FEncoding.GetBytes(IntToStr(Value)));
end;
procedure TStreamWriter.Write(Value: Char);
begin
WriteBytes(FEncoding.GetBytes(Value));
end;
procedure TStreamWriter.Write(Value: TObject);
begin
WriteBytes(FEncoding.GetBytes(Value.ToString));
end;
procedure TStreamWriter.Write(Value: Int64);
begin
WriteBytes(FEncoding.GetBytes(IntToStr(Value)));
end;
procedure TStreamWriter.Write(Value: Boolean);
begin
WriteBytes(FEncoding.GetBytes(BoolToStr(Value, True)));
end;
procedure TStreamWriter.WriteLine(Value: Double);
begin
WriteBytes(FEncoding.GetBytes(FloatToStr(Value) + FNewLine));
end;
procedure TStreamWriter.WriteLine(Value: Integer);
begin
WriteBytes(FEncoding.GetBytes(IntToStr(Value) + FNewLine));
end;
procedure TStreamWriter.WriteLine;
begin
WriteBytes(FEncoding.GetBytes(FNewLine));
end;
procedure TStreamWriter.WriteLine(Value: Boolean);
begin
WriteBytes(FEncoding.GetBytes(BoolToStr(Value, True) + FNewLine));
end;
procedure TStreamWriter.WriteLine(Value: Char);
begin
WriteBytes(FEncoding.GetBytes(Value));
WriteBytes(FEncoding.GetBytes(FNewLine));
end;
procedure TStreamWriter.WriteLine(Value: Int64);
begin
WriteBytes(FEncoding.GetBytes(IntToStr(Value) + FNewLine));
end;
procedure TStreamWriter.WriteLine(const aFormat: string; Args: array of const);
begin
WriteBytes(FEncoding.GetBytes(Format(aFormat, Args) + FNewLine));
end;
procedure TStreamWriter.WriteLine(Value: TObject);
begin
WriteBytes(FEncoding.GetBytes(Value.ToString + FNewLine));
end;
procedure TStreamWriter.WriteLine(Value: Single);
begin
WriteBytes(FEncoding.GetBytes(FloatToStr(Value) + FNewLine));
end;
procedure TStreamWriter.WriteLine(const Value: string);
begin
WriteBytes(FEncoding.GetBytes(Value + FNewLine));
end;
{$ENDIF FPC}
{other functions}
function CreateDummyFile(const aFilename : string; const aSize : Int64 ) : Boolean;
var
fs : TFileStream;
i : Integer;
buf : string;
Begin
Result := False;
fs := TFileStream.Create(aFilename,fmCreate);
buf := 'A';
try
fs.Seek(0, soBeginning);
for i := 0 to aSize do fs.Write(buf[1], Length(buf));
finally
fs.Free;
end;
Result := FileExists(aFilename);
End;
procedure SplitFile(const aFileName : string; aSplitByteSize : Int64);
var
fs, ss: TFileStream;
cnt : integer;
splitname: string;
begin
fs := TFileStream.Create(aFileName, fmOpenRead or fmShareDenyWrite) ;
try
for cnt := 1 to Trunc(fs.Size / aSplitByteSize) + 1 do
begin
splitname := ChangeFileExt(aFileName, Format('%s%.3d', ['.',cnt])) ;
ss := TFileStream.Create(splitname, fmCreate or fmShareExclusive) ;
try
if fs.Size - fs.Position < aSplitByteSize then
aSplitByteSize := fs.Size - fs.Position;
ss.CopyFrom(fs, aSplitByteSize) ;
finally
ss.Free;
end;
end;
finally
fs.Free;
end;
end;
procedure MergeFiles(const aFirstSplitFileName, aOutFileName : string);
var
fs, ss: TFileStream;
cnt: integer;
splitfilename : string;
begin
cnt := 1;
splitfilename := aFirstSplitFileName;
fs := TFileStream.Create(aOutFileName, fmCreate or fmShareExclusive) ;
try
while FileExists(splitfilename) do
begin
ss := TFileStream.Create(splitfilename, fmOpenRead or fmShareDenyWrite) ;
try
fs.CopyFrom(ss, 0) ;
finally
ss.Free;
end;
Inc(cnt) ;
splitfilename := ChangeFileExt(aFirstSplitFileName, Format('%s%.3d', ['.',cnt])) ;
end;
finally
fs.Free;
end;
end;
procedure MergeFiles(aFilenames : array of string; const aOutFileName : string);
var
filename : string;
fs,
ss : TFileStream;
begin
fs := TFileStream.Create(aOutFileName,fmCreate or fmShareExclusive) ;
try
for filename in aFilenames do
begin
if not FileExists(filename) then raise Exception.CreateFmt('Merge file %s not found!',[filename]);
ss := TFileStream.Create(filename, fmOpenRead or fmShareDenyWrite) ;
try
fs.CopyFrom(ss,0);
finally
ss.Free;
end;
end;
finally
fs.Free;
end;
end;
function IsFileInUse(const aFileName : string) : Boolean;
{$IFNDEF LINUX}
var
HFileRes: HFILE;
begin
Result := False;
if not FileExists(aFileName) then Exit;
try
HFileRes := CreateFile(PChar(aFileName),
GENERIC_READ or GENERIC_WRITE
,0
,nil
,OPEN_EXISTING
,FILE_ATTRIBUTE_NORMAL
,0);
Result := (HFileRes = INVALID_HANDLE_VALUE);
if not(Result) then begin
CloseHandle(HFileRes);
end;
except
Result := True;
end;
end;
{$ELSE}
var
fs : TFileStream;
begin
try
fs := TFileStream.Create(aFileName, fmOpenReadWrite, fmShareExclusive);
Result := True;
fs.Free;
except
Result := False;
end;
end;
{$ENDIF}
procedure FileReplaceText(const aFileName, aSearchText, AReplaceText : string);
var
fs: TFileStream;
S: string;
begin
fs := TFileStream.Create(aFileName, fmOpenread or fmShareDenyNone);
try
SetLength(S, fs.Size);
fs.ReadBuffer(S[1], fs.Size);
finally
fs.Free;
end;
S := StringReplace(S, aSearchText, AReplaceText, [rfReplaceAll, rfIgnoreCase]);
fs := TFileStream.Create(aFileName, fmCreate);
try
fs.WriteBuffer(S[1], Length(S));
finally
fs.Free;
end;
end;
function FileSearchText(const aFileName, SearchText: string; caseSensitive : Boolean): Longint;
const
BufferSize = $8001;
var
pBuf, pEnd, pScan, pPos: PAnsiChar;
filesize: LongInt;
bytesRemaining: LongInt;
bytesToRead: Integer;
F: file;
SearchFor: PAnsiChar;
oldMode: Word;
begin
Result := -1;
if (Length(SearchText) = 0) or (Length(aFileName) = 0) then Exit;
SearchFor := nil;
pBuf := nil;
AssignFile(F, aFileName);
oldMode := FileMode;
FileMode := 0;
Reset(F, 1);
FileMode := oldMode;
try
{$IFDEF FPC}
SearchFor := PChar(StrAlloc(Length(SearchText) + 1));
{$ELSE}
{$IFDEF DELPHI2010_UP}
SearchFor := PAnsiChar(StrAlloc(Length(SearchText) + 1));
{$ELSE}
SearchFor := StrAlloc(Length(SearchText) + 1);
{$ENDIF}
{$ENDIF FPC}
StrPCopy(SearchFor, SearchText);
{$IFDEF FPC}
if not caseSensitive then UpperCase(SearchFor);
{$ELSE}
if not caseSensitive then AnsiUpper(SearchFor);
{$ENDIF}
GetMem(pBuf, BufferSize);
filesize := System.Filesize(F);
bytesRemaining := filesize;
pPos := nil;
while bytesRemaining > 0 do
begin
if bytesRemaining >= BufferSize then bytesToRead := Pred(BufferSize)
else bytesToRead := bytesRemaining;
BlockRead(F, pBuf^, bytesToRead, bytesToRead);
pEnd := @pBuf[bytesToRead];
pEnd^ := #0;
pScan := pBuf;
while pScan < pEnd do
begin
{$IFDEF FPC}
if not caseSensitive then UpperCase(pScan);
{$ELSE}
if not caseSensitive then AnsiUpper(pScan);
{$ENDIF}
pPos := StrPos(pScan, SearchFor);
if pPos <> nil then
begin
Result := FileSize - bytesRemaining +
Longint(pPos) - Longint(pBuf);
Break;
end;
pScan := StrEnd(pScan);
Inc(pScan);
end;
if pPos <> nil then Break;
bytesRemaining := bytesRemaining - bytesToRead;
if bytesRemaining > 0 then
begin
Seek(F, FilePos(F) - Length(SearchText));
bytesRemaining := bytesRemaining + Length(SearchText);
end;
end;
finally
CloseFile(F);
if SearchFor <> nil then StrDispose(SearchFor);
if pBuf <> nil then FreeMem(pBuf, BufferSize);
end;
end;
{$IFDEF MSWINDOWS}
function GetLastAccessTime(const aFileName: string): TDateTime;
var
ffd: TWin32FindData;
dft: DWORD;
lft: TFileTime;
h: THandle;
begin
{$IFDEF FPC}
h := FindFirstFile(PAnsiChar(aFileName), ffd);
{$ELSE}
h := FindFirstFile(PChar(aFileName), ffd);
{$ENDIF}
if (INVALID_HANDLE_VALUE <> h) then
begin
FindClose(h);
FileTimeToLocalFileTime(ffd.ftLastAccessTime, lft);
FileTimeToDosDateTime(lft, LongRec(dft).Hi, LongRec(dft).Lo);
Result := FileDateToDateTime(dft);
end;
end;
function GetCreationTime(const aFilename : string): TDateTime;
var
ffd: TWin32FindData;
dft: DWORD;
lft: TFileTime;
h: THandle;
begin
{$IFDEF FPC}
h := FindFirstFile(PAnsiChar(aFileName), ffd);
{$ELSE}
h := FindFirstFile(PChar(aFileName), ffd);
{$ENDIF}
if (INVALID_HANDLE_VALUE <> h) then
begin
FindClose(h);
FileTimeToLocalFileTime(ffd.ftCreationTime, lft);
FileTimeToDosDateTime(lft, LongRec(dft).Hi, LongRec(dft).Lo);
Result := FileDateToDateTime(dft);
end;
end;
function GetLastWriteTime(const aFileName : string): TDateTime;
var
ffd: TWin32FindData;
dft: DWORD;
lft: TFileTime;
h: THandle;
begin
{$IFDEF FPC}
h := FindFirstFile(PAnsiChar(aFileName), ffd);
{$ELSE}
h := FindFirstFile(PChar(aFileName), ffd);
{$ENDIF}
if (INVALID_HANDLE_VALUE <> h) then
begin
FindClose(h);
FileTimeToLocalFileTime(ffd.ftLastWriteTime, lft);
FileTimeToDosDateTime(lft, LongRec(dft).Hi, LongRec(dft).Lo);
Result := FileDateToDateTime(dft);
end;
end;
{$ELSE}
function GetLastAccessTime(const aFileName: string): TDateTime;
var
info : stat;
begin
Result := 0;
if fpstat(aFileName,info) <> 0 then
begin
Result := info.st_atime;
end;
end;
function GetCreationTime(const aFilename : string): TDateTime;
var
info : stat;
begin
Result := 0;
if fpstat(aFileName,info) <> 0 then
begin
Result := info.st_ctime;
end;
end;
function GetLastWriteTime(const aFileName : string): TDateTime;
var
info : stat;
begin
Result := 0;
if fpstat(aFileName,info) <> 0 then
begin
Result := info.st_mtime;
end;
end;
{$ENDIF}
{$IFDEF FPC}
function FindDelimiter(const Delimiters, S: string; StartIdx: Integer = 1): Integer;
var
Stop: Boolean;
Len: Integer;
begin
Result := 0;
Len := S.Length;
Stop := False;
while (not Stop) and (StartIdx <= Len) do
if IsDelimiter(Delimiters, S, StartIdx) then
begin
Result := StartIdx;
Stop := True;
end