#include <iostream>
#include <fstream>
#include <string>
#include <conio.h>
#include<vector>
usingnamespace std;
int main () {
string temp;
vector<string>contain;
ifstream read_file ("D:\\example.txt"); // notice that you must use '\\' instead of '\' if you
// want to use directories
ofstream write_file ("test.txt");
cout << "this will copy the contain from 'D:\example.txt' to 'C:\test.txt'" << endl;
if(read_file.is_open())
while (getline(read_file,temp))
contain.push_back(temp);
else
{
cerr<<"Error opening file...";
return 1;
}
for(int i=0;i<contain.size();i++)
{
write_file<<contain[i];
}
cout << "press any key to continue...";
getch();
return 0;
}
Also the phrase on Line 15 is wrong. What this code will do, after it has been fixed, is copy the contents of "D:\example.txt" to ""path"test.txt" "path" being relative to the executable that is created when the code is compiled.
EDIT: You can fix that by changing line 13 of holtaf's code to:
1 2
ofstream write_file("C:\\test.txt", ios_base::app); /*This tags the data onto the end of the file
instead of overwritting it*/
If you do not close the open files then when the program is done executing the scheduler will do it for you. It's good practice to do this yourself though to avoid memory leaks in more complex programs.
The use of EXIT_SUCCESS and EXIT_FAILURE is slightly more portable (to non-Unix environments) than the use of 0 and some non-zero value like 1 or -1. In particular, VMS uses a different convention.