Can you please give me sort of exmaple program of app and ate?The ones on the net are too complicated and mixed with other programs.
I mean this ios::ate and ios::app in files.
#include <iostream>
#include <fstream>
#include <string>
void create_test_file( const std::string& path )
{
std::ofstream(path) // create if file does not exist, truncate if it exists
<< " line 1\n line 2\n line 3\n" ;
}
void debug_dump_file( const std::string& path )
{
std::cout << std::ifstream(path).rdbuf()
<< "\n-----------------------------------------------------\n" ;
}
int main()
{
const std::string test_file = "/tmp/test.txt" ;
create_test_file(test_file) ;
debug_dump_file(test_file) ;
{
// open the file for output and seek to the end of the file
// note: std::ios::in - open an existing file, do not truncate it
std::ofstream file( test_file, std::ios::in|std::ios::ate ) ;
file << "## line 4\n" ; // writes at the end of the file
file.seekp(0) ; // seek to the beginning
file << "## line 5\n" ; // writes at the beginning of the file
// (avances the put position by the number of characters written)
file << "## line 6\n" ; // writes at the current put position
}
debug_dump_file(test_file) ;
{
// open the file for output; all output is appended to the end of the file
// if the file exists, do not truncate it
std::ofstream file( test_file, std::ios::app ) ;
file << "** line 7\n" ; // appends at the end of the file
file.seekp(0) ; // seek to the beginning
file << "** line 8\n" ; // always appends at the end of the file
file.seekp(0) ; // seek to the beginning
file << "** line 9\n" ; // always appends at the end of the file
}
debug_dump_file(test_file) ;
}