C++ File Operations
// file_write.cpp
// Author: A.G.Raja
// Website: agraja.wordpress.com
#include <iostream>
#include <fstream>
using namespace std;
int main () {
ofstream myfile (“example.txt”);
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;
}
// g++ file_write.cpp
// file_read.cpp
// Author: A.G.Raja
// Website: agraja.wordpress.com
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main () {
string line;
ifstream myfile (“example.txt”);
if (myfile.is_open())
{
while (! myfile.eof() )
{
getline (myfile,line);
cout << line << endl;
}
myfile.close();
}
else cout << “Unable to open file”<<endl;
return 0;
}
//g++ file_read.cpp
Download here.
cpp_file_operations.doc