why do you close the file? there is a different cursor (wrong technical name I am sure but easier to think about it as a cursor) for inputs and outputs...since u are using fstream instead of ofstream or ifstream, you can read and write with same object. Open the file before the loop, then close it after, move the cursors back to beginning at start of loop with file1.seekp(0L, ios::beg) file1.seekg(0L, ios::beg). This will make teh code neater but I am not sure if that's an actual problem. I can't check it on my own computer since I accidentally delted my C++ software the other day...but only opening it once will make it easier to debug, even if it doesnt solve the problem.