xxxxxxxxxx
#include <fstream>
#include <string>
int main(int argc, char** argv)
{
std::ifstream ifs("myfile.txt");
std::string content( (std::istreambuf_iterator<char>(ifs) ),
(std::istreambuf_iterator<char>() ) );
return 0;
}
xxxxxxxxxx
// Reading a file
#include <iostream>
#include <fstream>
#include <string>
int main()
{
std::string line;
std::ifstream file("example.txt");
if(file.is_open())
{
while(getline(file, line))
{
std::cout << line << '\n';
}
file.close();
}
else std::cout << "Unable to open file";
return 0;
}
xxxxxxxxxx
#include <fstream>
#include <iostream>
using namespace std;
int main() {
/* You create a stream using the file in a
* similar way to how we use other streams.
*/
ifstream in;
// Open the file
in.open("names.txt");
if(in.fail())
cout << "File didn't open"<<endl;
int count = 0;
string line;
while (true) {
/* Get line will work as long as there is
* a line left. Once there are no lines
* remaining it will fail.
*/
getline(in, line);
if (in.fail()) break;
/* Process the line here. In this case you are
* just counting the lines.
*/
count ++;
}
cout << "This file has " << count << " lines." << endl;
return 0;
}
xxxxxxxxxx
// Create a text string, which is used to output the text file
string myText;
// Read from the text file
ifstream MyReadFile("filename.txt");
// Use a while loop together with the getline() function to read the file line by line
while (getline (MyReadFile, myText)) {
// Output the text from the file
cout << myText;
}
// Close the file
MyReadFile.close();
//https://www.google.com/url?sa=t&rct=j&q=&esrc=s&source=web&cd=&cad=rja&uact=8&ved=2ahUKEwi72ffun_D-AhXwh4sKHcB0A3UQFnoECAIQAQ&url=https%3A%2F%2Fwww.w3schools.com%2Fcpp%2Fcpp_files.asp&usg=AOvVaw1vZ4bdMEms4A0c4W27IrsT