Search code examples
c++fstream

C++ istream::read


Why this function read files wrong? In buff after read last symbols contain garbage values. Does it related with memory alignment? I know about more safe std::string and rdbuff(), but I want to understand how work C-style strings.

char * read_from_file(const char * path)
{
    std::ifstream fin(path);
    if (fin)
    {        
        fin.seekg(0, fin.end);
        size_t length = fin.tellg();
        fin.seekg(0, fin.beg);       
        
        char * buff = new char[length];
        fin.read(buff, length);
        
        std::cout << buff << "\n";

        fin.close();
        return buff;
    }
    return nullptr;
}

For example:

File:

#version 330 core

out vec4 FragColor;

void main()
{
    FragColor = vec4(1.0f, 0.5f, 0.2f, 1.0f);
}

buff:

#version 330 core

out vec4 FragColor;

void main()
{
    FragColor = vec4(1.0f, 0.5f, 0.2f, 1.0f);
}

isample_blit_scaled  <-- garbage

Solution

  • You need to add a null terminator to the string.

    char * read_from_file(const char * path)
    {
        std::ifstream fin(path, std::ios::binary);
        if (fin)
        {        
            fin.seekg(0, fin.end);
            size_t length = fin.tellg();
            fin.seekg(0, fin.beg);       
            
            char * buff = new char[length+1]; // allow room for terminator
            fin.read(buff, length);
            buff[length] = '\0'; // add terminator
            
            std::cout << buff << "\n";
    
            fin.close();
            return buff;
        }
        return nullptr;
    }