1

How can I remove all CRLF from a from a Base64 text file to make its content only on one line?

The following code uses a function, NoLineFeed, and a combination of TStringStream and AnsiString but still some CRLF are present (near the end of the file) after the content of the file have been processed by NoLineFeed.

function NoLineFeed was excerpted from a StackOverflow post by Arnaud Bouchez: Make String into only 1 line

var
    StringVal: AnsiString;
    XmlFile: TStringStream;
begin
    XmlFile := TStringStream.Create;
    try
        XmlFile.LoadFromFile('file.txt');
        StringVal := NoLineFeed(XmlFile.DataString);
        if Length(StringVal) > 0 then
            XmlFile.Write(StringVal[1], Length(StringVal));
        XmlFile.SaveToFile('converted_file.txt');
    finally
        XmlFile.Free;
    end;
end;

{ Arnaud Bouchez }
function NoLineFeed(const s: string): string;
var i: integer;
begin
  result := s;
  for i := length(result) downto 1 do
    if ord(result[i])<32 then
      if (i>1) and (ord(result[i-1])<=32) then
        delete(result,i,1) else
        result[i] := ' ';
end;
Fabio Vitale
  • 2,257
  • 5
  • 28
  • 38
  • 1
    Why not use what is proposed in the accepted answer, `str := StringReplace(str, #13#10, '', [rfReplaceAll]);` – LU RD Mar 15 '19 at 08:42
  • See [How to delete line-break in string which is encoded by the function EncodeString with Delphi 7?](https://stackoverflow.com/a/22489356/576719) – LU RD Mar 15 '19 at 09:45

2 Answers2

2

An alternative approach using a TStringList:

var
  lst: TStringList;
begin
  lst := TStringList.Create;
  try
    lst.LoadFromFile('file.txt');
    lst.LineBreak := ' ';
    lst.SaveToFile('converted_file.txt');
  finally
    lst.Free;
  end;
end;
Uwe Raabe
  • 45,288
  • 3
  • 82
  • 130
  • 1
    Thak you @UweRaabe!, I had to modify LineBreak from := ' '; := '' cause I want to remove the CRLF *without* replacing them wit #32 (space) – Fabio Vitale Mar 15 '19 at 11:49
0

Linebreaks and cariage return doesn't come always together, linebreaks sometimes come alone without cariage return and this may be the left linebreaks you have , just remove #13 characters and #10 characters separately will solve the problem ,try this code:

var
    StringVal: AnsiString;
    XmlFile: TStringStream;
begin
    XmlFile := TStringStream.Create;
    try
        XmlFile.LoadFromFile('file.txt');
        StringVal := StringReplace(XmlFile.DataString, #13, ' ', [rfReplaceAll]);
        StringVal := StringReplace(StringVal, #10, '', [rfReplaceAll]);
        if Length(StringVal) > 0 then
            XmlFile.Write(StringVal[1], Length(StringVal));
        XmlFile.SaveToFile('converted_file.txt');
    finally
        XmlFile.Free;
    end;
end;
ZORRO_BLANCO
  • 849
  • 13
  • 25