Stream is a flow of characters into or out to a program. In c++ we will use Stream class to make input and output operations.The Stream class as different classes to handle input and output data, The base class for the Stream is ios class
ifstream: This class represents the input stream data and will be used to read from the files
ofstream: This class represents the output stream data and will be used to write into the files
Some important point about I/O
Open a File in C++
To read or write any file first we need to open that file. To open the file ofstream or fstream will be used.
Syntax for open a file
void open(const char *filename, ios::openmode mode); |
In the above method first argument will the file location path and file name and second argument for the type of fileopen mode.
This mode will be
ios::app => This mode is for append the output at the end
ios::ate => This mode is for open a file output and control to the end of the file
ios::in => This mode is for open the file to read the content.
ios::out => This mode is for open the file to write the content.
ios::trunc => If the file already opened then its content will be truncated before open the current file
When we open a file we can apply 1 or more modes by adding OR condition
Example
ofstream outfile; |
How do i close a File in C++?
Normally when we terminate c++ program it automatically flushes all streams(input/output), then release allocated memory and close all the open files. But its a good practice the close the files manually by using close function.
Syntax
void close(); |
A simple c++ example on File Input and File output stream to read and write data on/from the files
#include <fstream> // open a file in write mode. cout << "Writing to the file" << endl; // write inputted data into the file. cout << "Enter your Lucky Number "; // close the opened file. // open a file in read mode. // write the data at the screen. // close the opened file. return 0; |
Conclusion: In this C++ article we covered what is stream and how to read and write files in cpp.
Article Contributed By :
|
|
|
|
860 Views |