The copy_files()
function first creates a new std::ofstream
object called output
and opens the file “new_file.txt”. It then uses a loop to iterate over the 10 text files, creating the file name using an std::ostringstream
object and reading the content of each file using an std::ifstream
object and an std::stringstream
object. It then writes the file name and content to the new file using the <<
operator. Note that we include newline characters and extra whitespace for readability. In the main()
function, we call copy_files()
.
#include <iostream>
#include <fstream>
#include <sstream>
void copy_files() {
std::ofstream output("new_file.txt");
for (int i = 1; i <= 10; i++) {
std::ostringstream file_name_stream;
file_name_stream << "file_" << i << ".txt";
std::string file_name = file_name_stream.str();
std::ifstream input(file_name);
std::stringstream buffer;
buffer << input.rdbuf();
std::string content = buffer.str();
output << "File name: " << file_name << "\nContent: " << content << "\n\n";
}
output.close();
}
int main() {
copy_files();
return 0;
}