You can read a file but can't write a file to save it

From TRCCompSci - AQA Computer Science
Jump to: navigation, search

I started by copying the ReadFile code, if the code reads the data it should tell you the order you need to write.

Examining the code each row of the field is written as a single line in the file, this is confirmed by the data file:

Data file.gif

Interestingly the vertical line character and the number at the end of the row are never read from the file. So my saved file looks like:

Saved data file.gif

The Code

 1  static void SaveFile(char[,] Field)
 2         {
 3             string FileName = "";
 4             Console.Write("Enter file name: ");
 5             FileName = Console.ReadLine();
 6             try
 7             {
 8                 StreamWriter CurrentFile = new StreamWriter(FileName);
 9                 for (int Row = 0; Row < FIELDLENGTH; Row++)
10                 {
11                     for (int Column = 0; Column < FIELDWIDTH; Column++)
12                     {
13                         CurrentFile.Write(Field[Row, Column]);
14                     }
15                     CurrentFile.WriteLine();
16                 }
17                 CurrentFile.Close();
18             }
19             catch (Exception)
20             {
21                 Console.WriteLine("Save field failed!!");
22             }
23         }

Explanation

I have swapped the StreamReader from the original code to StreamWriter. Inside the second for loop Write (Line 13) is used to add the value onto the end of the current line. Outside of the second for loop but inside the first for loop the WriteLine (Line 15) will write nothing onto the current line, but then move down to the next line.

You could extend this by check to see if the filename entered exists to avoid writing over that file.

Adding the save point

We now need to add a save point to the simulation. I decided to make the save point after it writes End of Simulation to the screen, the other possible places required more changes to the code itself. Another factor is that you want to save after each season has been simulated.

1      Console.WriteLine("End of Simulation");
2      Console.Write("Input X to save: ");
3      Response = Console.ReadLine();
4      if (Response == "x" || Response == "X")
5      {
6          SaveFile(Field);
7      }

Adding the row numbers to the save file

If you wanted to replicate the format of the original data file you could alter the CurrentFile.WriteLine command:

1 CurrentFile.WriteLine("| "+Row);

The original data file if the row was < 10 it had an extra space so they all lined up on the right edge:

1 if (Row <=9)
2      CurrentFile.WriteLine("|  " + Row);
3 else
4      CurrentFile.WriteLine("| " + Row);