Jul 26, 2009 at 3:52am UTC
instead of printing to screen
how can i overwrite my original file
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <iterator>
using namespace std;
int main()
{
vector <string> array;
std::ostream_iterator< string > output ( cout, "\n" );
ifstream read ( "letters3.txt" );
string line;
while ( getline ( read, line, '\n' ) )
{
array.push_back ( line );
}
read.close();
sort ( array.begin(), array.end() );
std::vector< string >::iterator endLocation;
endLocation = std::unique ( array.begin(), array.end() );
std::copy ( array.begin(), endLocation, output );
cin.get();
return 0;
}
Jul 26, 2009 at 4:00am UTC
I believe ifstream automatically deletes the contents of the file for you when you open a file with it. If it doesn't, use ios::trunc to delete them (it is passed as the second parameter of the constructor)
Jul 29, 2009 at 10:08pm UTC
ifstream does delete the contents of the file, unless the "app" flag is raised when opening the file.
ie:
1 2
ifstream newfile;
newfile.open("file.txt" );
will clear the file when it opens it, whereas
1 2
ifstream newfile;
newfile.open("file.txt" , ifsteam::app);
will keep the contents of the file and add to it
[edit] corrected the missing "i" in ifstream[/edit]
Last edited on Jul 29, 2009 at 10:09pm UTC