Quick help please

I am writing some data to a file but I do not know the information required in the third line until after the file is completed

is there a way to point the ofstream back to the beginning of the file so that i can edit it accordingly?

In some cases the file can be over a billion lines long so the information cannot be held in memory

My current code closes the file and then opens it again to edit the file

The lines I replace are exactly the same length

ofstream file_out(output_file);

//lots of output to file_out

file_out.close();

fstream file;
file.open(output_file);

file << "data file\n\n";

file << No_atoms << " atoms\n";

I hope I have given enough information

Thank you for your time

Look at this.

When you are about to write the value of No_atoms (which I guess is a dummy value at first), call tellp() before writing the dummy value and save the location value it returns. Afterwards, when you have a real value of No_atoms, use seekp() to get back to that position in the file and write No_atoms again. One thing to check for is that the length is the same, because it will overwrite characters of the original dummy value, so format the ofstream such that both the dummy value and the actual final value take up the same amount of characters (writing it in binary form would be also easier for that, but then you have to write the whole file in binary, which might not be a bad idea if the file is as long as you say it is).

Thank you

That works perfectly

Unfortunately the program that will read this information will not accept a binary input currently

>> Unfortunately the program that will read this information will not accept a binary input currently

yeah I thought so too, it seems like scientific code to me, and third-party software to load and analyse the data rarely accepts binary. It annoying to have to wait sometimes hours for the data to load in a software before it can be analysed.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.