C++ Opening file

tutorial and example
tutorial and example

C++ File Handling

File handling is a mechanism that manipulates the data stored in files. File handling store output data from program to external file and read file data to program. There are two types of communication takes place program.

  1. Data transfer between consol unit and program.
  2. Data transfer between program and disk file.

C++ Standard File Handling Class

C++ contains 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 file using istream.
  2. ofstream: this header file is used to write output file stream into 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 file into program.

The stream that supplies data from program to file is known as output stream. Output stream is used to write from program into file.

CPP File Handling 1

C++ file handling header files contains several functions for different operations.

Function Description
open() To create new file as well as open an existing file
close() To close an existing file
read() Read data from file
write() Write data into 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. 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

Example

C++ File Handling open() Function Example

Output: