I want to append data to a file in a function like so:
void Fill( string fileName ){
ofstream outputFile(fileName, ofstream::out | ofstream::app);
outputFile << data1 << " " << data2 << endl;
outputFile.close();
}
This function is then used in a loop to write to different files if certain conditions are met. But I want to begin with empty files when the program is run, i.e. not to append to old data. How can I do this? Hope I made this clear. Thanks!
The simplest solution would be to open all of the files your program uses without std::ofstream::app in some a function that you call once at the beginning in order to truncate them.
void resetFiles()
{
static char * fileNames[] = {
// Fill this with filenames of the files you want to truncate
};
for( int i = 0; i < sizeof( fileNames ) / sizeof( fileNames[ 0 ] ); ++i )
std::ofstream( fileNames[ i ] );
}
int main( int argc, char ** argv )
{
resetFiles();
...
}
EDIT: Since you did specify you're looking for more elegant solution, here's what I've come up with. Basically you declare a new class that inherits from std::ofstream with static std::map< std::string, bool > member called record. You add a constructor that lets you specify the filename. It then looks up if the file has been already opened once by checking if key fileName exists in record. If not, it opens it with std::ofstream::trunc and sets record[ fileName ] to true. This way, when the file is opened for the second time, it knows that it has to open it with std::ofstream::app.
class OutFile : public std::ofstream
{
static std::map< std::string, bool > record;
// Helper function
static std::ios_base::openmode hasBeenOpened( std::string fileName )
{
// Test if the key is present
if( record.find( fileName ) == record.end() )
{
record[ fileName ] = true;
return std::ofstream::trunc;
}
else
{
return std::ofstream::app;
}
}
public:
OutFile( const char * filename )
: std::ofstream( filename, hasBeenOpened( std::string( filename ) ) ) {}
};
// Don't forget to initialize record
map< std::string, bool > OutFile::record;