Search code examples
c++stringofstream

Use a string containing qutation marks to specify a filepath for ofstream in C++


I'm trying to pass a string as a path for an ofstream. I'm using the .c_str() function but the programm runns through without generating the file.

ifstream path_stream ("config.txt");
path_stream >> path;
path_stream.close();
ofstream datum (path.c_str());

The contents of config.txt is

"test.txt"

If I give that directly to ofstream, the program creates the file test.txt.
With the string it just runs the program without any output.


Solution

  • The problem is that you have put the filepath in your config.txt file in quotation marks.

    If I give that directly to ofstream, the program creates the file test.txt.

    I suppose you've tried

    ofstream datum ("test.txt");
    

    which is very different from

    ofstream datum ("\"test.txt\"");
                  // ^^        ^^
    

    as that's the equivalent of

    ofstream datum (path.c_str());
    

    after path was read from the file.

    So just remove the quotation marks from your config.txt file.