1. Open the file for input, read the lines in the file into a vector; close the file.
2. Modify the contents of the vector.
3. Open the file for output, write the contents of the vector into the file; close the file.
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <algorithm>
int main ()
{
constchar* const input_file_name = __FILE__ ; // put the name of the file here
constchar* const output_file_name = "output.txt" ; // put the name of the file here
// to write back into the same file, use the same file name for both input and output
std::vector<std::string> all_the_lines ;
{
// Open the file for input, read the lines in the file into a vector; close the file.
std::ifstream file(input_file_name) ;
std::string line ;
while( std::getline( file, line ) ) all_the_lines.push_back(line) ;
}
{
// Modify the contents of the vector
for( std::string& line : all_the_lines ) std::reverse( std::begin(line), std::end(line) ) ;
}
{
// Open the file for output, write the contents of the vector into the file; close the file.
std::ofstream file(output_file_name) ;
for( const std::string& line : all_the_lines ) file << line << '\n' ;
}
{
// to verify that the lines have been modified, dump the contents of the output file
std::cout << std::ifstream(output_file_name).rdbuf() ;
}
}