0

I am working on a Windows VC++ 2008 project, and trying to use fileIO to put stuff out in log files in a sub-directory. I am doing the following:

void MessageQueue::LogOut(thingEnum _thing){
    std::ofstream Output;
    Output.open("Output/MainLog.txt", std::ios::app);

    if (Output.is_open()){
        // writing stuff
    }
    Output.close();
}

I know that the ios::app will generate a file, but isn't it also able to generate folders as well, or do I need a different command to generate a folder for the files to exist in. when I get rid of the sub-directory in the code it works fine, and if I create the folder I can put the sub-directory code back.

note: I understand that I should technically open the file buffer the same line that I create the stream object. I did not because I plan to put the .open into a case switch (_thing) to have access to multiple files, and just change the stream.

gardian06
  • 1,496
  • 3
  • 20
  • 34

3 Answers3

2

std::ofstream cannot create directories, nor is there any support in standard C++ for doing so. You can use boost.Filesystem : create_directories, or on a POSIX system, use the POSIX function mkdir(). You can read more solutions at this StackOverflow question.

Community
  • 1
  • 1
Chiara Coetzee
  • 4,201
  • 1
  • 24
  • 20
1

You could use the _mkdir function before you call open.

http://msdn.microsoft.com/en-us/library/2fkk4dzw(v=vs.90).aspx

#include <direct.h>

void MessageQueue::LogOut(thingEnum _thing){

    if (_mkdir("Output\\") == 0) {
        std::ofstream Output;

        Output.open("Output\\MainLog.txt", std::ios::app);

        if (Output.is_open()){
            // writing stuff
        }
        Output.close();
   }
   else {
        // could not create directory
   }
}
Dave
  • 266
  • 1
  • 9
0

On Windows use the CreateDirectory call to make the folder.

Steve C
  • 647
  • 3
  • 6