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.
- ofstream: This Stream class signifies the output file stream and is applied to create files for writing information to files
- ifstream: This Stream class signifies the input file stream and is applied for reading information from files
- fstream: This Stream class can be used for both read and write from/to files.
Opening a file
- Bypassing filename in constructor at the time of object creation
- Using the open() function
Syntax – void open(const char* file_name,ios::openmode
mode);
- First argument - the name and format of the file with the address of the file.
- 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:
- ifstream ios::in
-
ofstream ios::out
- 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()
-Aadhiraj More
Great Work!
ReplyDeleteThank you
DeleteNice post!
ReplyDeleteThank you
DeleteGreat job
ReplyDeleteKeep it up👍
Thank You
DeleteYour blogs are amazing, keep posting
ReplyDelete