0

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?

ecstrema
  • 543
  • 1
  • 5
  • 20

1 Answers1

1

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.

Galik
  • 47,303
  • 4
  • 80
  • 117