Reputation:
I'm trying to copy the data in one text file to another 'new' text file. The first text file already exists in the directory of the .cpp file. The second text file is created by obtaining the name of it in the runtime. The problem i'm facing is that i can't see the 'new' file that is created. The same code works in codeblocks IDE(The 'new' second file is created), but in Visual studio it isn't created. Kindly help me out here.
char dat;
string wnam;
ifstream exs;
exs.open("test.txt",ios::in);
cout << "Enter the name of the second file\n";
getline(cin,wnam);
fstream cre;
cre.open(wnam.c_str());
while (exs.get(dat)) {
cre << dat;
}
cout <<"Done!";
exs.close();
cre.close()
Upvotes: 0
Views: 38
Reputation: 62015
No, the code does not "seem right". You see, according to the documentation, the functions you use both to open an existing file and to create a new file are supposed to set failbit
in case of failure. You do not seem to be doing any checking whatsoever for errors.
It is unlikely that the "current directory" when your program is running is the directory where your .cpp
file is located. So, what is most probably happening is that your program's "current directory" is something entirely different. (This is, by the way, also one of the things that can likely be different when trying with different IDEs.) So, the "new" file is created in that directory, and you just do not see it because you are looking in the wrong place. Also, the opening of "test.txt" has failed, because that's also not in the current directory, but you do not know it, because you are not checking for errors. You are never going to get anywhere if you are not always checking for errors.
Besides always checking failbit
, also try printing the current directory, and also converting your filenames to absolute pathnames and displaying them before trying to open them. Or try using a debugger. The debugger is an awesome invention.
Upvotes: 1