×

C++ File Handling

File handling is a mechanism that manipulates the data stored in files. File handling store output data from the program to external file and read file data to the program. There are two types of communication takes place program.
  1. Data transfer between the console unit and program.
  2. Data transfer between program and disk file.

C++ Standard File Handling Class

C++ contains a set of library classes that handle the file handling methods. These classes include:
  1. ifstream: this header file is used to read input file stream from the file using istream.
  2. ofstream: this header file is used to write output file stream into the file using ostream.
  3. fstream: this header file is used for both input and output operation and inherits all the function of istream and ostream thorough iostream.
The above classes are derived from fstreambase and from the corresponding iostream class.

Input and Output Stream

The stream that supplies data from file to program is known as input stream. Input stream is used to read the file into program. The stream that supplies data from the program to file is known as an output stream. The output stream is used to write from the program into file. C++ file handling header files contain several functions for different operations.
Function Description
open() To create a new file as well as open an existing file
close() To close an existing file
read() Read data from the file
write() Write data into the file
get() Read a single character from a file
put() Write a single character into a file

C++ File Handling Mode Parameter

Mode parameter in the file handling defines the specific purpose for which the file is opened. The mode parameter is always passed as the second parameter in the file handling methods. These modes are:
Mode Description
Ios::in Open file in read mode
Ios::out Open file in write mode
Ios::app Append to end of file
Ios::ate Go to end of file on opening
Ios::trunk Delete the content of the file if it exits

C++ File Handling open() Function

A file must be opened before doing any manipulation over it. The open() function is used to open a file either for read from or write into a file. Syntax
file-stream-class   file-stream-object;  
file-stream-object.open("filename");
Example
ofstream  outfile;        
outfile . open ("employee.txt");

C++ File Handling open() Function Example

#include <iostream>  
#include <fstream>  
using namespace std;  
int main () {  
  ofstream myfile;  
// open file employee.txt  
  myfile.open ("D:/Ashutosh/C++ Tutorial/C++ tutorial/employee.txt");// 
check file location  
  if(myfile.is_open()){  
    cout<<"File is open"<<endl;  
    myfile << "Writing into a file.\n";  
    myfile.close();  
  }  
  else{  
    cout<<"Error in file opening"<<endl;  
  }  
  return 0;  
}
Output: 


Related Topics

Sum of all elements between k1’th and k2’th Smallest Elements

In this tutorial, we will look at how to determine sum of all given elements between two given indexes’ smallest elements. Assuming an array of integers and two numbers, k1...

2 minutes read.

Factorial Program in C++

C++ Factorial Program: The product of all positive descending integers is the factorial of n. n! denotes the factorial of n. For instance: 5! = 5*4*3*2*1=120 4! = 4*3*2*1=24 In Combinations and Permutations, the...

4 minutes read.

C++ Memory Management

Memory management is a method of controlling computer memory and allocating memory space to applications to increase overall system performance. What is the purpose of memory management? Because the array contains homogeneous...

4 minutes read.

How to create the Processes with Fork in C++

 In this article, we are going to explain the different methods that help us to create processes with a fork(). There are two methods to do so. These methods are...

2 minutes read.

C++ Keywords

In this article, we will discuss keywords in C++ with their several features and functions. What are Keywords in C++? In C++, a keyword is a reserved word that has a predefined...

4 minutes read.

Copy elision in C++

The Copy Omission is another name for the Copy Elision. One of the several compiler optimization techniques is copy elision. It prevents items from being copied inadvertently. This Copy Elision approach...

3 minutes read.

Similarities between C++ and Java

People who are preparing for software engineering roles must have come across either one of these languages because as all the companies do not accept python for hiring a fresher...

3 minutes read.

Armstrong Number Program in C++

Let's first define Armstrong number before writing the C++ program to check whether the number is Armstrong or not. The sum of the cubes of its digits is equal to the...

2 minutes read.

How to Sort an Array in C++

What is Sorting? Sorting is a process of arranging elements in sequential order, either numerically or alphabetically. The sorting of a numerical array can be accomplished using a variety of algorithms,...

4 minutes read.

Stack in C++

Stack: The stack is a very popular data structure. It is the form of data structure that follows a particular order called FIFO(First-In-First-Out). In simple words, a stack is an Abstract...

4 minutes read.

C++ Bidirectional Iterators

Iterators : Iterators serve as a link between algorithms and STL containers, allowing the data inside the container to be modified. They let you to iterate through the container, access and...

3 minutes read.

C++ Dijkstra Algorithm Using the Priority Queue

In this article we will be finding the shortest routes from a source vertex in a graph to all vertices in the graph, given a graph and a source vertex...

5 minutes read.

C++ 11 vs C++ 14 vs C++ 17

C++ is a language that is used to create a high-performance application. C++ 11, C++ 14, and C++ 17 are the different version of C++. There are some differences between...

1 minute read.

C++ Structs

We frequently encounter scenarios in which we must store a bunch of data, whether of comparable or dissimilar data kinds. Arrays are used to hold a group of data of...

6 minutes read.

C++ Goto

In this article, we will discuss the C++ goto statement with its syntax, use, key features, key points, pseudo code, and examples. What is the goto statement in C++? In C++, the...

4 minutes read.

Static keyword in C++ vs Java

Both in C++ and Java, the static keyword is employed for essentially the same function. But there are some variations. The static keyword's similarities and differences between C++ and Java...

3 minutes read.

C++ Program For FCFS (First Come First Serve)

The most basic scheduling technique is FCFS, often known as "FIFO (First In, First Out)". In this procedure, the first one is utilized and executed first, while the second one...

4 minutes read.

Hybrid Inheritance

C++ Hybrid Inheritance When more than one type of inheritance is combined in single inheritance is called as hybrid inheritance. C++ Hybrid Inheritance Example #include<iostream>   using namespace std;   class Student{       protected:           int rollno;       public:           void getRoll(int a){               rollno=a;           }           void putRoll(void){               cout <<"Roll No: "<< rollno<<endl;           }   };   class Test : public Student{       protected:           float subject1, subject2;       public:           void getMarks(float x, float y){               subject1=x;               subject2=y;           }           void putMarks(void){               cout<< "Marks gain: "<<endl <<"Subject1 =  "<<subject1<<endl<<"Subject2 = "<<subject2 <<endl;           }   };   class Sport{       protected:           float score;       public:           void getScore(float s){               score=s;           }           void putScore(void){               cout<<"Sports score: "<<score<<endl;           }   };   class Result : public Test, public Sport{       float total;       public:           void display(void);   };   void Result:: display(void){       total=subject1+subject2+score;       putRoll();       putMarks();       putScore();       cout<<"Total Score: "<<total<<endl;   }   int main(){       Result stu;       stu.getRoll(10);       stu.getMarks(40,50);       stu.getScore(60);       stu.display();       return 0;   } Output: Roll No: 10 Marks gain: Subject1 = 40 Subject2 = 50 Sports score: 60 Total...

1 minute read.

How to Reverse a String in C++ using For Loop

For Loop: We may loop through a certain section of C++ code repeatedly using the for loop. A for loop is carried out if the test expression yields a true result. The...

4 minutes read.

C++ Tricks for Competitive Programming

If you are interested in Computer science or Information technology, you must have heard about competitive programming. Competitive programming is a way to improve your problem-solving skills. There are various...

7 minutes read.