-
No truncation?
I'm using std:: ofstream, and I'm trying to open a file without truncation. I know of std::ios::app, but I'm trying to write to the beginning of the file and std::ios::app makes every output go to the end of the file (even with std:: ofstream::seekp( 0, std::ios::beg )). I've been Googling/board searching for a while, and I've found several "solutions" that don't work. Some say std::ios::ate doesn't truncate, but it does, and I've found plenty of similar things that do the same. So how do I go about opening a file for writing, with truncating it, and so I still have the ability to write to the beginning of the file?
-
use ios::ate instead of ios::app
-
» use ios::ate instead of ios::app
As I said in my post, it still truncates for me. For example:
Code:
#include <iostream>
#include <fstream>
int main( void )
{
std::ofstream Out( "File.txt" );
if( !Out.is_open() )
{
return 0;
}
Out << "Triangle";
Out.close();
std::cin.get();
Out.open( "File.txt", std::ios::ate );
if( !Out.is_open() )
{
return 0;
}
Out << "Square";
Out.close();
return 0;
}
I run it, check the file, and it says "Triangle." Then I hit enter in the program, it closes, and I open the file again. Now it simply says "Square."
-
You can try:
Code:
#include <iostream>
#include <fstream>
int main( void )
{
std::ofstream Out( "File.txt" );
if( !Out.is_open() )
{
return 0;
}
Out << "Triangle";
Out.close();
std::cin.get();
Out.open( "File.txt", std::ios::ate | std::ios::out | std::ios::in );
if( !Out.is_open() )
{
return 0;
}
Out << "Square";
Out.close();
return 0;
}
-
Well, the example wasn't entirely accurate:
Code:
#include <iostream>
#include <fstream>
int main( void )
{
std::ofstream Out( "File.txt" );
if( !Out.is_open() )
{
return 0;
}
Out << "Triangle";
Out.close();
std::cin.get();
Out.open( "File.txt", std::ios::ate | std::ios::out | std::ios::in );
if( !Out.is_open() )
{
return 0;
}
Out.seekp( 0, std::ios::beg );
Out << "Square";
Out.close();
return 0;
}
The resulting file is:
So now I need to figure out how to not overwrite Triangle...
-
1) Assign your beginning of file text to a string variable.
2) Read the file into another string variable.
3) Add 1 and 2.
4) Write the result to the file.
-
> So now I need to figure out how to not overwrite Triangle...
There is no file insert functionality.
If you want to end up with
Square
Triangle
Then you need to open a whole new file for output, open the existing file for input, and copy data from the old file to the new file, intermixed with whatever new data you want to write.