Search code examples
c++stringfilestream

Cpp create string creation without initialization


I want to read the contents of a file into a string.

string contents(size, '\0'); -> size was determined above using the file.seekg and file.tellg.
file.read((char*) contents.data(), size);

Now, I know that the contents of the string will be overwritten in file.read, so there's no need to initialize the the string to null characters.

Is there a way to do so?


Solution

  • You can do this:

    std::string contents(std::istreambuf_iterator<char>{file},
        std::istreambuf_iterator<char>{});
    

    But it may not be faster. Either way the initialization is likely to be very fast in comparison to reading from the drive.