Reputation: 602
I am wanting to create a file in a folder using OFstream. The following lines of code - always Give "Output File could not be created...". No matter what I try.
Eventually I want to replace the JOHN part of the string, with a variable (type String).
Tips would be very much appreciated.
ofstream output_file(".\\Players\\JOHN\\Balance.txt", ios::app); // open the output file for appending
if (!output_file.is_open()) { // check for successful opening
cout << "Output file could not be opened! Terminating!" << endl;
_sleep(1000);
return 1;
}
else{
output_file << getAcctbal();
output_file.close();
return 0;
}
EDIT:
What have is a Players Folder - in that Players folder. for each individual Player I want to have a file (so John) is a Folder in this case. This folder doesn't exist, and is something I am trying to achieve. Thank you very much :-)
Upvotes: 1
Views: 6360
Reputation: 613572
Files can only be created in directories that already exist. So, you do need to force the directory structure to exist before you attempt to create the file.
There is no C++ standard library functionality that will do that. You can implement your own function to do that easily enough. Parse the path for its directory components. Starting at the highest point in the tree, create each sub-directory in turn.
You appear to be using Windows. The Windows API has functionality that serves your needs directly. Specifically the SHCreateDirectory
function. I don't know whether or not you are prepared to tie yourself to a platform specific API such as that – the choice is yours.
Upvotes: 3