lundi 28 mars 2022

Does std::string needs explicit resizing or does it handles resizing itself?

I am trying to write a std::string in a file and then reading it back. Why do i need to resize the string while reading back the text (see the commented line below while reading back the string)? Doesn't the string handles its size automatically?

#include <iostream>
#include <fstream>

int main()
{
    {
        std::ofstream ofile("c:\\out.txt", std::ios_base::binary);

        if (!ofile.is_open())
        {
            std::cout << "Failed to open the file";
            return 1;
        }

        std::string s = "Hello World";

        try
        {
            ofile.write(s.data(), s.size());
            if (ofile.fail())
            {
                std::cout << "Failed to write the file";
                return 1;
            }
        }
        catch (std::ios_base::failure& e)
        {
            std::cout << e.what();
        }



        ofile.close();
    }

    {
        std::ifstream ifile("c:\\out.txt", std::ios_base::binary);
        if (!ifile.is_open())
        {
            std::cout << "Unable to open input file";
            return 1;
        }
        ifile.seekg(0, std::ios::end);
        auto length = ifile.tellg();
        ifile.seekg(0, std::ios::beg);

        std::string outstr;
        //outstr.resize(length);
        try
        {
            ifile.read(reinterpret_cast<char*>(&outstr.front()), length);
        }
        catch (std::ios_base::failure& e)
        {
            std::cout << e.what();
        }

        std::cout << outstr;
    }
    return 0;
}

Aucun commentaire:

Enregistrer un commentaire