#include <iostream>
#include <fstream>
#include <cstdlib>
#include <cstring>
usingnamespace std;
// First text is undeclard
int main ()
{
string dataFile;
ifstream myfile ("test.txt");
if (myfile.is_open())
{
while (myfile)
{
char ch = myfile.get();
cout << ch;
if(ch!=EOF)
dataFile += ch;
}
myfile.close();
}
else
{
cout << "Unable to open file";
exit(-1);//Because I think You dont want to write in file with no data
}
ofstream file ("newfile.txt");
if (file.is_open())
{
file << dataFile;
file.close();
}
return 0;
}
You're reading through the original file line by line, then you write out the last line you read to the new file. You need to store each string you read in, then write out those strings in a loop to your new file.
#include <iostream>
#include <fstream>
int main()
{
constchar* const path_to_srce_file = "myfile.txt" ;
constchar* const path_to_dest_file = "newfile.txt" ;
// open the source file for text input
std::ifstream in( path_to_srce_file ) ;
// open the destination file for text output,
// truncate it if it exists, create it if it doesn't
std::ofstream out( path_to_dest_file ) ;
// copy the contents of the source file to the destination file
out << in.rdbuf() ;
}