4

I am using C++ and trying to output a file to a specific place, a folder with a specified name in the same directory as the executable. Couldn't find a great resource on an easy way to do this but I know it must be possible.

My example. I am saving a log file and instead of having it save to the same directory as the executable, it saves to /logs/

Thank you for your time!

Edit: I used mkdir to create a folder but how do I output to that folder. Is mkdir even a good thing to be using? I want to learn the best way to do this, not necessarily the easiest.

Satchmo Brown
  • 1,409
  • 2
  • 20
  • 47
  • Assuming that you are using mkdir () function call (by including sys/stat.h), and not a system ("mkdir"), your usage of mkdir() is fine. – Jaywalker May 03 '11 at 11:01

1 Answers1

6

This code:

#include <fstream>
#include <iostream>

int main()  {
    std::ofstream of( "C:\\mydir\\somewhere\\log.txt" );
    of << "hello\n";
}

will write "hello" to the file log.txt in the directory c:\mydir\somewhere, assuming the directory exists. And yes, mkdir is the right function to use. If you don't want to hardcode the path, you can find the path & name of the executable with GetModuleFileName, and then create the path programatically from that - see How to get Current Directory? for an example.

Community
  • 1
  • 1