You only hand data from the while loop to the write when the while loop is terminated...that's the way data flow works (nothing exits the loop until the loop is terminated...and it's only the data from the last iteration that exits, unless you keep the previous data in a buffer in e.g a shift register).
If you want to write the data from each iteration you need to either put the string building and file write function inside the loop, or build a 2D array of all the 1D arrays you generate and then write that 2D array when the while loops finishes...(in the latter case it's best to initialize a shift register with a 2D array of the correct size and then replace rows/columns inside the loop...not build the array on each iteration as that requires continous memory alloca
tion, which is memory costly and slow...).
If you decide to write on each iteration I would recommend not using the write characters to file function as this opens and closes the file every time..insetad open/create the file prior to entering the while loop, write on each iteration and then close when the while loop terminates...(if the loop is to run a lot of times it may be possible to optimize performance by combining the two approaches; keep X iterations in memory and just write on every X itertaion...).