Reading all the data from a file

Mar 15, 2016 at 5:38am
I know how to read data from a file using fin using a given amount of variables, but I want to know how to read 'all' the data from the .txt file till the end.
Mar 15, 2016 at 8:11am
Read to dynamically reallocating container(s), like std::vector.
Mar 15, 2016 at 9:19am
http://www.cplusplus.com/reference/istream/istream/seekg/

Alternatively,
1
2
3
4
5
6
7
8
std:ifstream inFile{ "text.txt" };
if ( inFile.is_open( ) )
{
	std::stringstream buffer;
	buffer << inFile.rdbuf( );
	
	std::cout << buffer.str( ) << "\n";
}
Mar 15, 2016 at 11:03am
You don't actually have to check that the file is open before using the rdbuf() trick.

Also, seekg() is only useful on binary files, unfortunately. (They screw up on non-binary...)
Mar 15, 2016 at 2:36pm
If it's a text file, I think the simplest way is std::string::getline()

1
2
3
4
5
    std::string AllTextInFile, temp;
    std::ifstream File("1.txt");
    getline(File,temp);
    AllTextInFile=temp;
    while(getline(File,temp))AllTextInFile+="\n"+temp;
Topic archived. No new replies allowed.