concat.pp 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120
  1. { Concatenates a number of text files. This code is in the public domain. }
  2. program concat;
  3. uses
  4. SysUtils, Classes;
  5. var
  6. Dst: TextFile;
  7. FileList: TStringList;
  8. IgnoreNonExisting: boolean;
  9. procedure usage;
  10. begin
  11. Writeln('Usage: concat [-i] <srcfile1> [<srcfile2> ..] <dstfile>');
  12. Writeln;
  13. Writeln('Options:');
  14. Writeln(' -i Ignore non-existent files');
  15. Writeln;
  16. halt(1);
  17. end;
  18. procedure DoConcat;
  19. var
  20. Src: TextFile;
  21. I: Longint;
  22. Line: Ansistring;
  23. OldFilemode: byte;
  24. begin
  25. OldFilemode:=FileMode;
  26. Filemode:=0;
  27. for I:=0 to FileList.Count-1 do
  28. begin
  29. Assign(Src,FileList[i]);
  30. {$i-}
  31. Reset(Src);
  32. while ioresult<>0 do
  33. begin
  34. { wait for lingering locks to disappear }
  35. Sleep(200);
  36. Reset(Src);
  37. end;
  38. {$i+}
  39. while not Eof(Src) do
  40. begin
  41. ReadLn(Src,Line);
  42. Writeln(Dst,Line);
  43. end;
  44. Close(Src);
  45. end;
  46. Filemode:=OldFilemode;
  47. Close(Dst);
  48. end;
  49. procedure CheckParas;
  50. var
  51. FirstFile,
  52. I: Longint;
  53. Exists: boolean;
  54. begin
  55. { enough parameters? }
  56. if ParamCount<2 then
  57. Usage;
  58. FirstFile:=1;
  59. if UpperCase(ParamStr(1))='-i' then
  60. begin
  61. IgnoreNonExisting:=true;
  62. Inc(FirstFile);
  63. end;
  64. { check destination }
  65. if DirectoryExists(ParamStr(ParamCount)) then
  66. begin
  67. Writeln('Destination "',ParamStr(ParamCount),'" is a directory');
  68. halt(2);
  69. end;
  70. Assign(Dst,ParamStr(ParamCount));
  71. {$i-}
  72. Rewrite(Dst);
  73. {$i+}
  74. if IOResult<>0 then
  75. begin
  76. Writeln('Unable to create destination file "',ParamStr(ParamCount),'"');
  77. halt(2);
  78. end;
  79. { check source(s) }
  80. for I:=FirstFile to ParamCount-1 do
  81. begin
  82. Exists:=True;
  83. if not FileExists(ParamStr(I)) then
  84. begin
  85. if not IgnoreNonExisting then
  86. begin
  87. Writeln('File "',ParamStr(I),'" does not exist');
  88. halt(2);
  89. end;
  90. Exists:=False;
  91. end
  92. else if DirectoryExists(ParamStr(I)) then
  93. begin
  94. Writeln('"',ParamStr(I),'" is a directory');
  95. halt(2);
  96. end
  97. else if Exists then
  98. FileList.Add(ParamStr(I));
  99. end
  100. end;
  101. begin
  102. FileList:=TStringList.Create;
  103. CheckParas;
  104. DoConcat;
  105. FileList.Free;
  106. end.