What i'm trying to do :
I'm running a loop to print a list of words in a .txt file with ofstream.
Once i exit this loop i go back to the beginning of the file with seekp(0, ios::beg) and insert the number of words processed by the loop.
My problem: When i insert my counter at the beginning of the file, it overwrites the first characters of my file.
Of course i have the dirty solution of typing blankspaces before starting with my list, so the characters overwritten are not lost data, but if possible i'm looking for a real solution to my problem, that can give me a clean output file (without extra blankspace or without the risk of loosing data if one day i process too many words).
Also I thought about writing the file only once i exited my loop with my word count and my word list buffered in a string, but the lists i process are huge and i'm assuming that buffering the whole list in a string is less efficient that writing directly in the file word by word. Am I right?
Sorry i don't have my code to show right now, hope the explanations are clear enough, if not i'll edit later :)
There is no such thing as insertion in file. File is like a sheet of paper. You cannot really insert line between two existing ones. Only way is to erase everything after point of insertion, write additional content and wrile old content again.
Another approach is to have temporary file with your list, then create new file, write counter and then write temporary file content here:
1 2 3 4 5
int counter = /*..*/;
std::ifstream tmp("TMPFILE");
std::ofstream out("proper_file");
out << counter << '\n';
out << tmp.rdbuf();