Originally Posted by
cerin
Is there any easy way to read the entire file than the one below? So I only have to change a few things?? Or at least a couple lines instead of one?
If you are simply trying to store the entire contents of a text file in a mass buffer of some kind in as few steps as possible then there are at least a couple of options for you:
You could store everything in a string:
Code:
#include <iostream>
#include <fstream>
#include <string>
#include <algorithm>
#include <iterator>
int main()
{
std::string str;
std::ifstream input("hi.txt");
// Read entire file into string container...
input.unsetf(std::ios::skipws); // Preserve/store whitespace characters
std::copy(std::istream_iterator<char>(input),std::istream_iterator<char>(),
std::inserter(str,str.end()));
// Output file contents to cout...
std::cout << str << std::endl;
}
You can also use a stringstream:
Code:
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
int main()
{
std::stringstream str;
std::ifstream input("hi.txt");
// Read entire file into stringstream...
str << input.rdbuf();
// Output file contents to cout...
std::cout << str.str() << std::endl;
}
Given a file hi.txt containing the following:
Code:
hi there
hi there
hi there
hi there
Then of course the output should be:
Code:
hi there
hi there
hi there
hi there