Creating the same text file over and over

Hi everyone,

I need to create a program that writes a text file in the current folder, the text file always contains the same information, for example:

1
2
3
4
5
Hello,
This is an example of how the text file may look
some information over here
and here
and so on


So I was thinking in doing something like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
#include <fstream>

using namespace std;

int main(){
	ofstream myfile("myfile.txt");
	myfile << "Hello," << endl;
	myfile << "This is an example of how the text file may look" << endl;
	myfile << "some information over here" << endl;
	myfile << "and here" << endl;
	myfile << "and so on";
	
	myfile.close();
	return 0;
}


Which works if the number of lines in my text file is small, the problem is that my text file has over 2000 lines, and I'm not willing to give the myfile << TEXT << endl; format to every line.

Is there a more effective way to create this text file?
Thanks.
@ntran

Use a for loop, like so..

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main()
{
string 	TEXT[5]={"Hello,","This is an example of how the text file may look",
"some information over here","and here","and so on.."};
ofstream myfile("myfile.txt");
for(int x=0;x<5;x++)
	myfile << TEXT[x] << endl;
	
	myfile.close();
	return 0;
}
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
#include <fstream>

using namespace std;

const char* text =
R"(Hello,
This is an example of how the text file may look
some information over here
and here
and so on
)";

int main(){
    std::ofstream("myfile.txt") << text;
}
Create the text file once (using a text editor) in a specific directory -
say /home/ntran/template_files/myfile.txt or c:\users\ntrans\template_files\myfile.txt

Then to create a copy of the file in the current directory:
1
2
3
4
5
6
7
8
9
10
11
#include <fstream>

int main()
{
   // make a copy of c:\users\ntrans\template_files\myfile.txt in the current directory
   {
       const char* const srce_path = "c:/users/ntrans/template_files/myfile.txt" ;
       const char* const dest_path = "myfile.txt" ;
       std::ofstream(dest_path) << std::ifstream(srce_path).rdbuf() ;
   }
}
Last edited on
Topic archived. No new replies allowed.