
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
File Handling Through C++ Classes
In this tutorial, we will be discussing a program to understand File Handling through C++ classes.
What's File Handling?
File handling is an important concept in programming, which allows a program to read from and write to files. C++ has built-in classes and functions for file handling, which is done using file stream classes that are part of the <fstream>
- ofstream: This class is used for output file streams, where it allows the user to write data to files.
- ifstream: This class is used for input file streams, where it allows users to read data from files.
- fstream: This class combines both input and output file stream capabilities, Where which allows users to read from and write to the same file.
Example
Here is the following implementation of ifstream and ofstream functions.
#include <iostream> #include <iostream> #include <fstream> using namespace std; int main() { //creating ofstream object ofstream fout; string line; fout.open("sample.txt"); //initiating loop if file is opened while (fout) { getline(cin, line); if (line == "-1") break; fout << line << endl; } fout.close(); ifstream fin; fin.open("sample.txt"); while (fin) { getline(fin, line); cout << line << endl; } fin.close(); return 0; }
Advertisements