0

I'm having a little trouble of converting a file to a string. This post is a continuation of this post.

This is the function I'm calling:

std::string fileToString(std::string const& file){

    std::ifstream in(file);
    if (!in){
        std::cout << "Error: file does not exist\n"; 
        exit(EXIT_FAILURE);
    }

    std::stringstream buffer;
    buffer << in.rdbuf() << std::flush;
    in.close();

    return buffer.str();
}

And I called this to test it out:

std::ofstream file("test.txt");
file << fileToString("fileTest.txt").c_str();

In my scenario, I have to end up returning a char*, so in the end I want it to work like this: (where GLchar is a typedef for char in OpenGL)

const GLchar* vertexShaderSource = fileToString("Shaders\\shader.vsglsl").c_str();

However, this time, the test.txt file is empty. What happened here?

Community
  • 1
  • 1
  • 1
    "However, this time, the test.txt file is empty" Are you still writing to test.txt? Based on the code snippet you've provided it doesn't look like it. – MrEricSir Oct 31 '15 at 19:17
  • Mind that if you use that `GLchar*`, you again get undefined behaviour because you are (again) taking a pointer to a temporary. You should fix this by keeping the value returned by `fileToString` in a named object. – Christian Hackl Oct 31 '15 at 19:24

0 Answers0