Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

filehandling.cpp #2519

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
59 changes: 59 additions & 0 deletions C++/filehandling.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
/* File Handling with C++ using ifstream & ofstream class object*/
/* To write the Content in File*/
/* Then to read the content of file*/
#include <iostream>

/* fstream header file for ifstream, ofstream,
fstream classes */
#include <fstream>

using namespace std;

// Driver Code
int main()
{
// Creation of ofstream class object
ofstream fout;

string line;

// by default ios::out mode, automatically deletes
// the content of file. To append the content, open in ios:app
// fout.open("sample.txt", ios::app)
fout.open("sample.txt");

// Execute a loop If file successfully opened
while (fout) {

// Read a Line from standard input
getline(cin, line);

// Press -1 to exit
if (line == "-1")
break;

// Write line in file
fout << line << endl;
}

// Close the File
fout.close();

// Creation of ifstream class object to read the file
ifstream fin;

// by default open mode = ios::in mode
fin.open("sample.txt");

// Execute a loop until EOF (End of File)
while (getline(fin, line)) {

// Print line (read from file) in Console
cout << line << endl;
}

// Close the file
fin.close();

return 0;
}