Forum > Other

How to Convert ANSI format file into UTF8 format

(1/2) > >>

RaviMore9:
Hello All,

I would like to convert Same ANSI format file into UTF8 file without generating another file. (I want to convert same ANSI file into UTF8 format).
Is there any function available to convert ANSI file format to UTF8 format?

Eg,
Test_file.txt(ANSI format) ---> Test_file.txt (UTF8 format) 



Thanks in advance.

KodeZwerg:

--- Code: Pascal  [+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i < x.length; i++) { x[i].style.maxHeight='none'; x[i].style.height = Math.min(x[i].clientHeight+15,306)+'px'; x[i].style.resize = "vertical";}};} ---//https://forum.lazarus.freepascal.org/index.php/topic,60635.msg454159.html#msg454159program Project1; {$APPTYPE CONSOLE} Uses  SysUtils, Classes; function FileANSItoUTF8(const AFilename: string; const WriteBOM: Boolean = True): Boolean;var  Input, Output: TStringList;  i: Integer;begin  Result := False;  Input  := nil;  Output := nil;  if (not FileExists(AFilename)) then    Exit;  try    Input  := TStringList.Create;    try      Input.LoadFromFile(AFilename, TEncoding.ANSI);      Output := TStringList.Create;      try        Output.WriteBOM := WriteBOM;        for i := 0 to Pred(Input.Count) do          Output.Add(AnsiToUTF8(Input.Strings[i]));        Output.SaveToFile(AFilename, TEncoding.UTF8);      finally        Output.Free;        Output := nil;      end;    finally      Input.Free;      Input := nil;    end;    Result := i > 0;  except    if (Output <> nil) then      Output.Free;    if (Input <> nil) then      Input.Free;  end;end; var  s: string;begin  WriteLn('Convert ANSI to UTF8 - by KodeZwerg 2022 for forum.lazarus.freepascal.org');  if (ParamCount > 0) then    begin      s := ParamStr(1);      WriteLn('Converting: ' + s);      if FileANSItoUTF8(s) then        WriteLn('Success!')        else        WriteLn('Failed!');    end    else      WriteLn('Usage: ' + ParamStr(0) + ' "ANSI encoded file.txt"');  WriteLn('Press RETURN to continue.');  ReadLn;end.
Please test this. You might play a little with second Parameter (WriteBOM) to get what you want.

Thaddy:
Why do you use a loop? You can convert in one go using
--- Code: Pascal  [+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i < x.length; i++) { x[i].style.maxHeight='none'; x[i].style.height = Math.min(x[i].clientHeight+15,306)+'px'; x[i].style.resize = "vertical";}};} ---Output.Text :=AnsiToUTF8(Output.Text);Output.WriteBom := true;  // will be called before save and savetofile goes through a savetostreamOutput.SaveToFile(<your file>);This will result in an UTF8 file with BOM. BOM is optional.
And nilling evreywhere is also strange since the stringlists are local. I would rewrite your code something like this:
--- Code: Text  [+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i < x.length; i++) { x[i].style.maxHeight='none'; x[i].style.height = Math.min(x[i].clientHeight+15,306)+'px'; x[i].style.resize = "vertical";}};} ---{$mode objfpc}{$H+}uses classes, sysutils;function FileANSItoUTF8(const AFilename: string; const WriteBOM: Boolean = True): Boolean;var  Input, Output: TStringList;begin  Result := False;  if FileExists(AFilename) then  try    Input  := TStringList.Create;    try      Input.LoadFromFile(AFilename, TEncoding.ANSI);      Output := TStringList.Create;      try        Output.WriteBOM := WriteBOM;        Output.Text := AnsiToUTF8(Input.Text);      finally        Output.Free;      end;     finally        Input.Free;    end;    Result := true;  except    On E:Exception do        writeln (E.Message);  end;end; var  s: string;begin  WriteLn('Convert ANSI to UTF8 - by KodeZwerg 2022 for forum.lazarus.freepascal.org');  if ParamCount > 0 then    begin      s := ParamStr(1);      WriteLn('Converting: ' + s);      if FileANSItoUTF8(s) then        WriteLn('Success!')        else        WriteLn('Failed!');    end    else      WriteLn('Usage: ' + ParamStr(0) + ' "ANSI encoded file.txt"');  WriteLn('Press RETURN to continue.');  ReadLn;end.

KodeZwerg:
I do nil to free if something bad happen and not produce memory leaks.
I do loop to set Result.
I do set BOM optional with a switch and it does not matter where you set it since it is just a boolean.

KodeZwerg:

--- Quote from: Thaddy on September 19, 2022, 03:03:06 pm ---Why do you use a loop? You can convert in one go using
--- Code: Pascal  [+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i < x.length; i++) { x[i].style.maxHeight='none'; x[i].style.height = Math.min(x[i].clientHeight+15,306)+'px'; x[i].style.resize = "vertical";}};} ---Output.Text :=AnsiToUTF8(Output.Text);Output.WriteBom := true;  // will be called before save and savetofile goes through a savetostreamOutput.SaveToFile(<your file>);This will result in an UTF8 file with BOM. BOM is optional.
And nilling evreywhere is also strange since the stringlists are local. I would rewrite your code something like this:
--- Code: Text  [+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i < x.length; i++) { x[i].style.maxHeight='none'; x[i].style.height = Math.min(x[i].clientHeight+15,306)+'px'; x[i].style.resize = "vertical";}};} ---{$mode objfpc}{$H+}uses classes, sysutils;function FileANSItoUTF8(const AFilename: string; const WriteBOM: Boolean = True): Boolean;var  Input, Output: TStringList;begin  Result := False;  if FileExists(AFilename) then  try    Input  := TStringList.Create;    try      Input.LoadFromFile(AFilename, TEncoding.ANSI);      Output := TStringList.Create;      try        Output.WriteBOM := WriteBOM;        Output.Text := AnsiToUTF8(Input.Text);      finally        Output.Free;      end;     finally        Input.Free;    end;    Result := true;  except    On E:Exception do        writeln (E.Message);  end;end; var  s: string;begin  WriteLn('Convert ANSI to UTF8 - by KodeZwerg 2022 for forum.lazarus.freepascal.org');  if ParamCount > 0 then    begin      s := ParamStr(1);      WriteLn('Converting: ' + s);      if FileANSItoUTF8(s) then        WriteLn('Success!')        else        WriteLn('Failed!');    end    else      WriteLn('Usage: ' + ParamStr(0) + ' "ANSI encoded file.txt"');  WriteLn('Press RETURN to continue.');  ReadLn;end.
--- End quote ---
Your code does save nothing.

Navigation

[0] Message Index

[#] Next page

Go to full version