C++ To Delphi Translation needed

Hi All,

Can someone please translate the next block of code for me from C++ to Delphi:

//------------------------------------------------------------------------------------------------

   int  nCount;
   char MyString[500];
   TListItem* aLi1;
   AnsiString BadWordsFileName = ExtractFilePath(Application->ExeName) + "pkwhitelist.dat";

   
   FILE*   ptrf = fopen(BadWordsFileName.c_str(), "r");
   if (ptrf == NULL)
   {  return;
   }

   fscanf(ptrf, "%d\n", &nCount);

   if(nCount==0)
   { fclose(ptrf);  ListView1->Items->Clear();
     return;
   }

   ListView1->Items->Clear();

   for (INT i = 0; i < nCount; i++)
   {
          fscanf(ptrf, "%s\n", MyString);
          ListView1->Items->BeginUpdate(); // Efficiency

          aLi1 = ListView1->Items->Add();
          aLi1->Caption = MyString;
          ListView1->Items->EndUpdate();
   }

   fclose(ptrf);

//------------------------------------------------------------------------------------------------

Thanks in advance
GiantMatrixAsked:
Who is Participating?
 
mokuleCommented:
I've missed also Clear Items

Once more whole code

var
  i: integer;
  nCount: integer;
  BadWordsFileName: string;
  f: textFile;
  MyString: string;
  aLi1: TListItem;
begin
  BadWordsFileName := ExtractFilePath(Application.ExeName) + 'pkwhitelist.dat';
  AssignFile(f,BadWordsFileName);
  try
    reset(f);
    readln(f,MyString);
    nCount := StrToIntDef(MyString,0);
    if nCount > 0 then
      ListView1.Items.Clear;
    ListView1.Items.BeginUpdate;
    for i := 0 to nCount-1 do
      begin
      aLi1 := ListView1.Items.Add;
      readln(f,MyString);
      aLi1.Caption := MyString;
      end;
    ListView1.Items.EndUpdate;
    CloseFile(f);
  except
  end;
end;
0
 
mokuleCommented:
This is translation with some improvements

var
  i: integer;
  nCount: integer;
  BadWordsFileName: string;
  f: textFile;
  MyString: string;
  aLi1: TListItem;
begin
  BadWordsFileName := ExtractFilePath(Application.ExeName) + 'pkwhitelist.dat';
  AssignFile(f,BadWordsFileName);
  try
    reset(f);
    readln(f,MyString);
    nCount := StrToIntDef(MyString,0);
    ListView1.Items.BeginUpdate; // better do it outside loop
    for i := 0 to nCount do
      begin
      aLi1 := ListView1.Items.Add;
      readln(f,MyString);
      aLi1.Caption := MyString;
      end;
    ListView1.Items.EndUpdate;
    CloseFile(f);
  except
  end;
end;
0
 
mokuleCommented:
sorry a small bug, should be
    for i := 0 to nCount-1 do
0
 
GiantMatrixAuthor Commented:
Hi mokule,

Can you help me with how to write to a file the content of Items in ListView1->Items?

If you can please let me know and I will open a new question for it in EE

Thanks in advance

0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.