Reputation: 85
I'm learning about Input/Output with files in C++. I can compile my file, receive no error, but the file execution does not provide the result I expect. I have looked on internet for an answer, but could not find it.
This is the C++ code:
// basic file operations
#include <iostream>
#include <fstream>
using namespace std;
int main () {
ofstream myfile;
myfile.open ("example.txt");
myfile << "Writing this to a file.\n";
myfile.close();
return 0;
}
I have created an empty "example.txt" file in which it can write. But I believe that the algorithm does not find that file on my computer though. Is that the problem? Thank you for your help.
Upvotes: 1
Views: 5340
Reputation: 603
Your algorithm will create file in directory where your executive file exactly is. If it doesn't exist - ofstream will create a new one. If you want to write to particular file, you should pass the absolute file path to ofstream.open, e.g. myfile.open("C:\temp\example.txt");
Upvotes: 1
Reputation: 56549
myfile.open ("example.txt");
If there is not such a file, it will create a new file. So, the problem is not searching for an existing file.
Maybe your program hasn't the permission to create a file.
Upvotes: 1