Search code examples
c++directoryofstream

c++ change directory of ofstream with a string buffer filename


I have this line of code

    std::ofstream output(p_strFilename.c_str());

where p_strFilename is defined from a function parameter

    foo(const std::string &p_strFilename)

which is saving a bunch of files in the current working directory. However I want to enter a step inside that directory and save the files inside. I tried

    std::ofstream output("folder1\\"+p_strFilename.c_str())

this is giving me

    error: invalid operands of types ‘const char [9]’ and ‘const char*’ to binary ‘operator+’

which I guess is reading the directory as 9 characters instead of as a string.

First question: Is that the right way to input a directory? (double backslash and starting from the CWD not form home directory)

Second question: How can I resolve my compilation error?


Solution

  • I think you need to convert to c_string only after the concatenation:

    std::ofstream output(("folder1/"+p_strFilename).c_str())
    

    Hope it helps! :)