One problem is that your "sort condition" function is probably using the incorrect comparison operator.
Also you didn't answer my question second question. What is the state of the stream when you try to write to the stream? Remember when you read the file you stopped when eof() was encountered. Normally if a stream is in an error state you must first clear the error, then reposition the stream to the desired position.
Reading and writing to the same stream with an fstream can be fairly tricky. IMO it would be much easier to use two different streams, one ifstream, one ofstream.
@jib thank you for your answer,
I could fix my code with your help.
I didn't answer your second question because I don't answer. (I don't understand your question well)
Fixed code with two different streams but how can I fix it with one stream? (fstream)
Fixed code with two different streams but how can I fix it with one stream? (fstream)
The problem is that you read the stream till eof(), causing a stream error flag to be set. Once a stream enters an error state you must clear the error prior to trying to preform any other read or write operation. And you will probably want to reset the file pointer to the start of the file if you intend to overwrite the file contents.