Question:
I want to split a TXT file into smaller TXT files. The program should split the file every time there are three empty lines. For example:
Paragraph1
Paragraph2
Paragraph1 and Paragraph 2 would become separate text files. I would be grateful if you could tell me which commands I should use or even build such program if it isn't too difficult.
Answer:
That's an interesting problem. Assuming that you won't ever need to go back to an original file, you can use the same file variable to handle all the destination files. It's just a matter of counting. Here's wrapper procedure that ought to work.
procedure CreateABunchOfFiles(SourceFile : String);
var
fSource,
fDest : TextFile;
buf : String;
BlankCounter,
DestCounter : Integer;
begin
//Let's initialize the variables
DestCounter := 1;
BlankCounter := 1;
AssignFile(fSource, SourceFile);
Reset(fSource);
AssignFile(fDest, 'Dest' + IntToStr(DestCounter) + '.TXT');
Rewrite(fDest);
//Now go through the file line by line
while NOT EOF(fSource) do begin
ReadLn(fSource, buf);
//Make sure we remove all trailing and leading spaces
//to catch blank lines. If we come across a blank line,
//then skip the rest of processing and move to the next
//one. This is ultra important because some text files'
//blank lines contain spaces or null characters, they'll
//be read as real bytes.
if (TrimLeft(TrimRight(buf)) = '') then
Inc(BlankCounter);
else
//Okay, we've come across three blank lines in a row
if (BlankCounter = 3) then
begin
//Reset the counter
BlankCounter := 1;
//Close current destination file
CloseFile(fDest);
//Increment the Destination File ID (DestCounter)
Inc(DestCounter);
//Open up a new file based on the new name
AssignFile(fDest, 'Dest' + IntToStr(DestCounter) +
'.TXT');
Rewrite(fDest);
end
else
//Otherwise, just write the line to the current
destination
WriteLn(fDest, buf);
end;
end;
This solution is pretty straightforward File I/O stuff, so I won't go into detail here. Look over the logic to understand how it works. I commented it pretty well so you can follow it easily.