I think what rafae11 meant was to do all your reading from file before you write to the file.
You open the file for both reading and writing with two separate file streams. So in other words when you are done reading do fin.close(); then do fout.open("1.txt");