First, if it's a text file made by several lines, I find the std::string
class not a good choice as a "container"; I would prefer just a std::vector<char>
, or if you want to do some additional parsing and break the file into its single lines, a std::vector<std::string>
.
I'd also pay attention to the encoding used by the file: is it UTF-8? Is it some other char
-based encoding?
For example, if the file is UTF-16, reading it as a raw sequence of bytes into a std::string
would be very misleading (and bug prone).
Moreover, it's important also to pay attention to the size of the file. If you have a gigantic text file (e.g. 5GB) and you are building a 32-bit Windows application, your code won't work (as 32-bit processes on Windows are limited to 2GB by default). In such cases, reading the file content in smaller chunks (or using memory-mapped file techniques with smaller "views" on the file) may be a better alternative.