C++ File Handling

File Handling in C++

File are used to store the user data for extended time periods. As such the data is stored in permanent device storage. Thus, File handling becomes an essential mechanism to store the output of program or to receive inputs for a program and other various operations.
To receive and send data to and from a device, stream is used as an abstraction. Stream is represented as source or destination of characters of indefinite length.

In C++, file handling can be done using libraries, as such, ifstream, ofstream and fstream provide the needed functionality. These classes are derived from fstrembase and corresponding iostream class. Thus, any C++ program involving must include fstream library, as these classes are a part of the library.

In C++, files are mainly dealt by using three classes fstream, ifstream, ofstream.

  1. ofstream: This Stream class signifies the output file stream and is applied to create files for writing information to files
  2. ifstream: This Stream class signifies the input file stream and is applied for reading information from files
  3. fstream: This Stream class can be used for both read and write from/to files.

Opening a file
  1. Bypassing filename in constructor at the time of object creation
  2. Using the open() function
open() function
Syntax – void open(const char* file_name,ios::openmode mode);
  1. First argument - the name and format of the file with the address of the file.
  2. Second argument - mode in which the file is to be opened


Mode
Description
in
Opens the file to read(default for ifstream)
out
Opens the file to write(default for ofstream)
binary
Opens the file in binary mode
app
Opens the file and appends all the outputs at the end
ate
Opens the file and moves the control to the end of the file
trunc
Removes the data in the existing file
nocreate
Opens the file only if it already exists
noreplace
Opens the file only if it does not already exist
Default Open Modes:
  1. ifstream ios::in
  2. ofstream ios::out
  3. fstream ios::in | ios::out
We can combine the different modes using or symbol | .
Close a File
It is simply done with the help of close() function.
Syntax – File Pointer.close()






Comments

Post a Comment

Popular posts from this blog

Operator Overloading in C++

Application Linked list