Example, I have a sample.txt
file with content:
1 2 3 7 8 9 10
and I want to insert 4 5 6
in file to have
1 2 3 4 5 6 7 8 9 10
so that numbers are inserted in the right place.
Example, I have a sample.txt
file with content:
1 2 3 7 8 9 10
and I want to insert 4 5 6
in file to have
1 2 3 4 5 6 7 8 9 10
so that numbers are inserted in the right place.
Files generally don't support inserting text in the middle. You should read the file, update the contents and overwrite the file.
Use a sorted container, e.g. std::set
to hold the contents of the file in memory.
std::set<int> contents;
// Read the file
{
std::ifstream input("file");
int i;
while (input >> i)
contents.insert(i);
}
// Insert stuff
contents.insert(4);
contents.insert(5);
contents.insert(6);
// Write the file
{
std::ofstream output("file");
for (int i: contents)
output << i << ' ';
}