Search code examples
c++arraysvariablesofstream

c++ ofstream write_to_log.open (" relative path + array");


I want the line below to write a new file using the content given in the array but into a new folder named logs:

char log_file_name[100]; /* this array contains the name of a new file */

ofstream write_to_log;
write_to_log.open (relative path, log_file_name , fstream::app); 

How do I get it working ?


Solution

  • You can use CreateDirectory for creating folders with VC++ in Windows.

    #include <windows.h>
    #include <string>
    #include <fstream>
    using namespace std;
    
    int main() {
       string path = "C:\\users\\folder";
       CreateDirectory(path.c_str(), NULL);
    
       char log_file_name[100] = "log.txt";
       path += '\\';
       path += log_file_name;
       ofstream write_to_log(path.c_str(), fstream::app);
    
       return 0;
    }
    

    The NULL refers to a security attributes structure that you may have to create. More details at MSDN here and in this answer.