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
#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
fstream input;
input.open("Data.txt", ios::in);
string city;
if (input.fail())
{
cout << "File does not exist" << endl;
cout << "Exit program" << endl;
}
while (!input.eof()) // Continue if not end of file
{
getline(input, city, '.');//getline(file,string,delimit char)
cout << city << endl;
}
input.close();
//Another solution
fstream file2;
file2.open("Data.txt", ios::in);
string line;
cout << "Data file: \n";
if (file2.is_open()) { //check if the file is open
while (getline(file2, line)) {
cout << line << endl;
}
file2.close();
}
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
xxxxxxxxxx
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
string fileName;
int choice;
cout << "Enter txt file name:\n";
cin >> fileName;
cout << "Enter number of command:\n";
cout << "1. Write file\n";
cout << "2. Read file\n";
cin >> choice;
if (choice == 1)
{
ofstream myfile;
string text;
myfile.open (fileName);
cout << "Write text below: \n"; //file must have no text
cin >> text;
myfile << text;
myfile.close();
}else if (choice == 2)
{
ifstream file(fileName);
string line;
if (file.is_open())
{
while (getline(file, line))
{
cout << line << endl;
}
}
}
return 0;
}