1

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 :-)

KingJohnno
  • 602
  • 2
  • 12
  • 31
  • Are you sure the directories `Players` and `Players\JOHN` exist relative to the current working directory? (That may not be the same directory as your executable.) – Joe Z Dec 07 '13 at 20:47
  • No, the Folder JOHN is the one that I want to create. Within that Folder I want to create a Folder called DETAILS.txt – KingJohnno Dec 07 '13 at 20:47
  • Maybe you don't have access rights to create it? – Caesar Dec 07 '13 at 20:49
  • 2
    Opening a file does not create directories (aka. folders). You need to use a different API for that. I'm not sure what the best Windows API is for that, but in POSIX (aka. UNIX, Linux), `mkdir()` is what you want. Windows may support that too, as it has some POSIX support. I'm not a Windows expert, though. – Joe Z Dec 07 '13 at 20:49
  • 1
    @JoeZ - That is where I have been going wrong! I've always thought that OFstream would create it for me :L – KingJohnno Dec 07 '13 at 20:50

1 Answers1

3

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.

David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490