Objects of the class fstream
are used for general file operations. With this class it is possible to write to and read from files.
fstream myFile;
myFile.open(filename, ios::out | ios::in);
#include <fstream>
#include <iostream>
using namespace std;
int main() {
string str;
fstream myFile;
myFile.open("textfile.txt", ios::out);
if (myFile.is_open()) {
myFile << "New line to text file" << endl;
myFile.close();
} else {
cout << "Unable to open text file";
}
return 0;
}
[textfile.txt]
New line to text file
#include <fstream>
#include <iostream>
using namespace std;
int main() {
string str;
fstream myFile;
myFile.open("Documents/website/codevisionz/textfile.txt", ios::in);
if (myFile.is_open()) {
while (!myFile.eof()) {
getline(myFile, str);
cout << str << endl;
}
myFile.close();
} else {
cout << "Unable to open text file";
}
return 0;
}
New line to text file