Skip to main content

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

26
  • 6
    open is definitely a method of ifstream, however the 2nd parameter is wrong. cplusplus.com/reference/iostream/ifstream/open Commented Apr 8, 2010 at 17:30
  • 9
    @KeithB If efficiency is important, you could find the file length the same was as in the char* example and call std::string::reserve to preallocate the necessary space. Commented Apr 8, 2010 at 17:36
  • 57
    No sure why people are voting this up, here is a quick question, say I have a 1MB file, how many times will the "end" passed to the std::string constructor or assign method be invoked? People think these kind of solutions are elegant when in fact they are excellent examples of HOW NOT TO DO IT. Commented Mar 10, 2011 at 8:49
  • 121
    Benchmarked: both Tyler's solutions take about 21 seconds on a 267 MB file. Jerry's first takes 1.2 seconds and his second 0.5 (+/- 0.1), so clearly there's something inefficient about Tyler's code. Commented Oct 1, 2012 at 12:32
  • 9
    The insanecoding blog post is benchmarking solutions to a slightly different problem: it is reading the file as binary not text, so there's no translation of line endings. As a side effect, reading as binary makes ftell a reliable way to get the file length (assuming a long can represent the file length, which is not guaranteed). For determining the length, ftell is not reliable on a text stream. If you're reading a file from tape (e.g., a backup), the extra seeking may be a waste of time. Many of the blog post implementations don't use RAII and can therefore leak if there's an error. Commented Oct 14, 2013 at 22:56