I can explain the problem to you, but the fix is up to you (because my C++ file i/o abilities aren't particularly strong).
The problem you have is that in a recursive function, you keep opening the same file for writing. The first time you write, and return, the file stores the first line of output.
The second time you write, the file is opened again (thus overwriting the old file) and a second line is written.
So on, and so forth, until the last line. The last line overwrites the second last line, and the program terminates. That is why you have only the last line in the file.
The solution is to either open the file once outside of the function call, or to reopen it with an append mode (this is where I can't help with code, because I'm not quite sure how to do this) before writing and to make sure to close it after writing.
There might be some other effect you have with opening files that you do not close until the function exists, but it's "probably ok" (meaning, you shouldn't have it). That is, the first call to the function does not write anything, but it keeps an open handle until every other call of the function has written, and only closes the file afterwards... This might cause some weird behaviour, but then again it might not.