Create separate program file for each mode.
:
// writing on a text file using ios::app
#include <iostream>
#include <fstream>
using namespace std;
int main () {
ofstream myfile ("example.txt", ios::app);
if (myfile.is_open())
{
myfile << "This is a line.\n";
myfile << "This is another line.\n";
myfile.close();
}
else cout << "Unable to open file";
return 0;
}
// writing on a text file using ios::ate
#include <iostream>
#include <fstream>
using namespace std;
int main () {
ofstream myfile ("example.txt", ios::ate);
if (myfile.is_open())
{
myfile << "This is a line.\n";
myfile << "This is another line.\n";
myfile.close();
}
else cout << "Unable to open file";
return 0;
}
// writing on a text file using ios::binary
#include <iostream>
#include <fstream>
using namespace std;
int main () {
ofstream myfile ("example.txt", ios::binary);
if (myfile.is_open())
{
myfile << "This is a line.\n";
myfile << "This is another line.\n";
myfile.close();
}
else cout << "Unable to open file";
return 0;
}
// reading a text file using ios::in
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main () {
string line;
ifstream myfile ("example.txt", ios::in);
if (myfile.is_open())
{
while ( getline (myfile,line) )
{
cout << line << '\n';
}
myfile.close();
}
else cout << "Unable to open file";
return 0;
}
// writing on a text file using ios::nocreate
#include <iostream>
#include <fstream>
using namespace std;
int main () {
ofstream myfile ("example.txt", ios::nocreate);
if (myfile.is_open())
{
myfile << "This is a line.\n";
myfile << "This is another line.\n";
myfile.close();
}
else cout << "Unable to open file";
return 0;
}
// writing on a text file using ios::noreplace
#include <iostream>
#include <fstream>
using namespace std;
int main () {
ofstream myfile ("example.txt", ios::noreplace);
if (myfile.is_open())
{
myfile << "This is a line.\n";
myfile << "This is another line.\n";
myfile.close();
}
else cout << "Unable to open file";
return 0;
}
// writing on a text file usiong ios::out
#include <iostream>
#include <fstream>
using namespace std;
int main () {
ofstream myfile ("example.txt", ios::out);
if (myfile.is_open())
{
myfile << "This is a line.\n";
myfile << "This is another line.\n";
myfile.close();
}
else cout << "Unable to open file";
return 0;
}
// writing on a text file using ios::trunc
#include <iostream>
#include <fstream>
using namespace std;
int main () {
ofstream myfile ("example.txt", ios::trunc);
if (myfile.is_open())
{
myfile << "This is a line.\n";
myfile << "This is another line.\n";
myfile.close();
}
else cout << "Unable to open file";
return 0;
}
Comments
Leave a comment