File input output the last line of the output file is repeating infinite more times

My comments above are incorrect about clearing failbit and eofbit (only the single parameter overload of seekg clears eofbit), seekg sets failbit on error however, not eofbit, so your loop condition is never met.

From [istream.unformatted]

basic_istream<charT,traits>& seekg(off_type off, ios_base::seekdir dir);

Effects: Behaves as an unformatted input function (as described in, paragraph 1), except that it does not count the number of characters extracted and does not affect the value returned by subsequent calls to gcount(). After constructing a sentry object, if fail() != true, executes rdbuf()->pubseekoff(off, dir, ios_base::in). In case of failure, the function calls setstate(failbit) (which may throw ios_base::failure).

Change your condition to while (! or even better while (sample) to test for any stream error, or while(sample.get(ch)) to abort on the first read error.

Leave a Comment