0% found this document useful (0 votes)
16 views

Basic File Operations

This C++ code document provides examples of basic file input/output operations including writing text to a file, writing multiple lines to a file, and reading from a file and outputting the lines. It uses ofstream and ifstream to open files for writing and reading, writes text to files using <<, reads line by line using getline, and checks if files open successfully with is_open().

Uploaded by

smpalaniappan
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views

Basic File Operations

This C++ code document provides examples of basic file input/output operations including writing text to a file, writing multiple lines to a file, and reading from a file and outputting the lines. It uses ofstream and ifstream to open files for writing and reading, writes text to files using <<, reads line by line using getline, and checks if files open successfully with is_open().

Uploaded by

smpalaniappan
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 2

// basic file operations

#include <iostream>
#include <fstream>
using namespace std;

int main () {
ofstream myfile;
myfile.open ("example.txt");
myfile << "Writing this to a file.\n";
myfile.close();
return 0;
}

// writing on a text file


#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;
}
// reading a text file
#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";

return 0;
}

You might also like