How do I save the contents of this 2d array to a file

前端 未结 3 1239
情话喂你
情话喂你 2021-01-21 22:53

I Need some help trying to save the contents of the 2d array into a file. First of all im not sure what type the file should be etc .txt or dat.

I have edited the post s

3条回答
  •  走了就别回头了
    2021-01-21 23:11

    To answer your main question, you can save a two-dimensional string array as follows:

    procedure TForm9.FileSaveClick(Sender: TObject);
    var
      i, j: integer;
      fn: string;
      fs: TFileStream;
      fw: TWriter;
    begin
      fn := 'c:\tmp\mychessfile.dat';
      fs := nil;
      fw := nil;
      try
        fs := TFileStream.Create(fn, fmCreate or fmShareDenyWrite);
        fw := TWriter.Create(fs, 1024);
        for i := 1 to BoardDimension do
          for j := 1 to BoardDimension do
            fw.WriteString(Board[i, j]);
      finally
        fw.Free;
        fs.Free;
      end;
    end;
    

    Subsequently you can read the file back to the array with:

    procedure TForm9.FileReadClick(Sender: TObject);
    var
      i, j: integer;
      fn: string;
      fs: TFileStream;
      fr: TReader;
    begin
      fn := 'c:\tmp\mychessfile.dat';
      fs := nil;
      fr := nil;
      try
        fs := TFileStream.Create(fn, fmOpenRead or fmShareDenyWrite);
        fr := TReader.Create(fs, 1024);
        for i := 1 to BoardDimension do
          for j := 1 to BoardDimension do
              Board[i, j] := fr.ReadString;
      finally
        fr.Free;
        fs.Free;
      end;
    end;
    

    As you see I chose the general purpose .dat extension, because the file will contain also binary data, like length of each text, data type etc. Those details are dealt with by the TWriter/TReader classes.

    You should also consider the comments you received regarding choise of file structure. For example, Googling for 'chess file format' (assuming you are working on a chess game), brings up Portable_Game_Notation and another reference from that page: Forsyth-Edwards Notation.

提交回复
热议问题