No no no...
If you want to slurp up an entire file in a string...
1 2 3 4 5 6 7
|
std::string readfile( const std::string& filename )
{
std::ifstream f( filename.c_str() );
std::ostringstream ss;
ss << f.rdbuf();
return ss.str();
}
|
This should perform quite admirably. Keep in mind that it does not do anything with platform-specific line endings or locale encodings. That is, on Windows, your string will have embedded "\r\n"s for newline instead of just "\n".
http://stackoverflow.com/questions/2602013/read-whole-ascii-file-into-c-stdstring
Write it back to file easily enough:
1 2 3 4 5 6
|
bool writefile( const std::string& filename, const std::string& s )
{
std::ofstream f( filename.c_str() );
f << s << flush;
return f.good();
}
|
Notice the lack of an
endl or anything like that there.
If you do plan to use a vector of strings (instead of your stated single string value), then you must take care to read the lines properly, and not just 'word' by 'word', as that loses all whitespace formatting the original text had.
1 2 3 4 5 6 7 8 9
|
std::vector <std::string> readfile( const std::string& filename )
{
std::vector <std::string> result;
std::ifstream f( filename.c_str() );
std::string s;
while (std::getline( f, s ))
result.emplace_back( s );
return result;
}
|
This also performs quite admirably. It is a text-file-only operation, and the resulting vector will not have any newline information at all (as newlines are extracted by the
getline() function).
You can write it back easily enough:
1 2 3 4 5 6 7 8
|
bool writefile( const std::string& filename, const std::vector <std::string> & v )
{
std::ofstream f( filename.c_str() );
for (const std::string& s : v)
f << s << "\n";
f << flush;
return f.good();
}
|
Notice that this time we make sure to add the newlines back into the file. Due to platform and locale considerations, this may produce a
different file than the original (say, if you read a *nix file and write it on Windows). The textual information will be the same, of course.
Uh, I don't think I missed anything important...
Hope this helps.