Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

#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);
    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;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading