Mega Code Archive

 
Categories / Delphi / Examples
 

Brutesearch

EXAMPLE PROCEDURES THAT USE THE BRUTE-FORCE SEARCH ALGORITHM, FOR READING A SOURCE FILE AND WRITING ALL OTHER TEXT BESIDES TEXT SPECIFIED BY THE USER TO ANOTHER FILE (NEED DEBUGGING BUT THEY'RE CLOSE...) function TParseForm.LoadSourceExclusive: Integer; {OK we're duplicating some code here but, search methods for grabbing the bulk of a file SHOULD be different, and though we might have integrated what happens here with LoadSourceExclusive above, this way is MUCH easier to follow} var startMatch: Boolean; i, filePos: LongInt; tempArray: array[0..pattArrayLen] of Char; bytesRead, bytesWritten, counter: Integer; lastCharsPos: LongInt; readFlag: Integer; begin filePos := 0; counter := 0; {assign a file handle and open input file...} AssignFile(srcFile, srcFileName); {assign a file handle and open output file....} AssignFile(destFile, destFileName); try {try to open source file...} reset(srcFile, 1); fileBytes := FileSize(srcFile); lastCharsPos := fileBytes - LongInt(prePattLen); {and try to open destination file...} reWrite(destFile); try repeat startMatch := True; while (startMatch = True) do begin blockRead(srcFile, tempArray, prePattLen, bytesRead); Inc(counter); Inc(filePos); i := 1; repeat if not(preSequence[i] = tempArray[i - 1]) then begin startMatch := False; break; end; Inc(i); until (i = prePattLen); if (i = prePattLen) then begin startMatch := True; break; end; end; if (startMatch = True) then begin filePos := ReadUntilSuccSeq; end else begin if (filePos = 1) then Write(destFile, tempArray[0]); if (((counter mod prePattLen) = 0) or (filePos = lastCharsPos)) then begin for i := 0 to (prePattLen - 1) do begin Write(destFile, tempArray[i]); end; end; Seek(srcFile, filePos); end; until (filePos >= fileBytes); finally begin closefile(srcFile); closeFile(destFile); end; end; {putting source file data into memory} except on E: EInOutError do begin MessageDlg('Error reading ' + uppercase(SRCFileName) + '.'#13 + GetError(E.ErrorCode)+'.', mterror,[mbOK], 0); readFlag := -1; end end; {trying to open source file} {if there hasn't been an error reading the source file then return the total number of blockreads that have been performed. If there has been an error then return -1...} Result := readFlag; end; function TParseForm.ReadUntilSuccSeq: LongInt; var endMatch: Boolean; i, filePos: LongInt; tempArray: array[0..pattArrayLen] of Char; bytesRead, bytesWritten: Integer; begin repeat endMatch := True; while (endMatch = True) do begin blockRead(srcFile, tempArray, succPattLen, bytesRead); Inc(filePos); i := 1; repeat if not(succSequence[i] = tempArray[i - 1]) then begin endMatch := False; break; end; Inc(i); until (i = succPattLen); if (i = succPattLen) then begin endMatch := True; break; end else Seek(srcFile, filePos); end; until ((filePos >= fileBytes) or (endMatch = True)); Result := filePos; end;