Tell me, good people, how can I solve such a task in Delphi, I want to shorten the code if of course as possible as I want

My task in the loop is to create 21 files in one loop, and not to write a bunch of duplicate code like for example below

Example:

Assignfile(AFile, ExtractFilePath(Application.ExeName)+'@a.txt'); Rewrite(AFile); Closefile(AFile); Assignfile(BFile, ExtractFilePath(Application.ExeName)+'@b.txt'); Rewrite(BFile); Closefile(BFile); .... 

the decision was such

 var Tfile: array [0..21] of TextFile; //созданиС массива для созданиС Ρ„Π°ΠΉΠ»ΠΎΠ² A: array [0..21] of string; // созданиС массива для ΠΈΠΌΠ΅Π½ Ρ„Π°ΠΉΠ»ΠΎΠ² //Π·Π°ΠΏΠΎΠ»Π½Π΅Π½ΠΈΠ΅ массива ΠΈΠΌΠ΅Π½Π°ΠΌΠΈ procedure TForm1.FormCreate(Sender: TObject); begin A[0] := '@a'; A[1] := '@b'; end; //созданиС Ρ„Π°ΠΉΠ»ΠΎΠ² с Π½ΡƒΠΆΠ½Ρ‹ΠΌΠΈ ΠΈΠΌΠ΅Π½Π°ΠΌΠΈ<br> procedure TForm1.StartClick(Sender: TObject); var j: integer; begin for j := 0 to 20 do begin Assignfile(Tfile[j], ExtractFilePath(Application.ExeName)+ A[j] + '.txt'); Rewrite(Tfile[j]); Closefile(Tfile[j]); end; end; 

now to the problem how to write data to the created files now

 Append(Tfile[A]); Writeln(Tfile[A],Filez.Strings[num_theards]); Closefile(Tfile[A]); 

I understand that there should be a string, and I pass the index and the types are not compatible with the array string, how can I solve this?

  • If the file is text, then it is more convenient to use TStringList. .Add add a line to it, there is a method SaveToFile (filename). Before SaveToFile, put Try except .. LoadFromFile - read the file. In short, it is more convenient at times, not to mention the fact that there is sorting and searching inside TStringList. - Albert Fomin

2 answers 2

Question decided, after sitting a little, on reflection

 Append(Tfile[A]); Writeln(Tfile[A], Filez.Strings[num_theards]); Closefile(Tfile[A]); 

only instead of the array of names A I substituted the variable N result I needed and equated it with the file name so that it recognizes, say, 1 this a and it all worked.

    An example of how to work with a file (everything seems to be clear here). ( source ):

     var myFile : TextFile; text : string; begin // ΠŸΠΎΠΏΡ‹Ρ‚ΠΊΠ° ΠΎΡ‚ΠΊΡ€Ρ‹Ρ‚ΡŒ Test.txt Ρ„Π°ΠΉΠ» для записи AssignFile(myFile, 'Test.txt'); ReWrite(myFile); // Π—Π°ΠΏΠΈΡΡŒ Π½Π΅ΡΠΊΠΎΠ»ΡŒΠΊΠΈΡ… извСстных слов Π² этот Ρ„Π°ΠΉΠ» WriteLn(myFile, 'Hello World'); // Π—Π°ΠΊΡ€Ρ‹Ρ‚ΠΈΠ΅ Ρ„Π°ΠΉΠ»Π° CloseFile(myFile); end; 

    Your code:

     ... Writeln(Tfile[A], Filez.Strings[num_theards]); ... 

    What does Filez.Strings[num_theards] ? Is it an array of strings? You can not do this ?:

     Filez.Strings[num_theards].Text