A file is a location or information, usually stored on a computer’s disk. Information can be saved to files and then later reused.
Setting Up a Program for file Input/Output-
Before file I/O can be performed, a C++ program must be set up properly.
File access requires the inclusion of fstream.h
In C++ Files, We use the fstream library, include both the standard <iostream> and the <fstream> header file is as follows:
Opening a File
The First argument specifies the name and location of the file to be and the second argument of the open() member function defines the mode in which the file should be opened.
You can two or more of these value by ORing them together. For Example if want to open a file write mode and want to truncate it in case is already exists, following will be the syntax:
Objectname.open(“filename”mode of the file);
Filename with extension
Closing a file
When a C++ program terminates it automatically close flushes all the streams, release all the allocated memory and close all opened files. But it is always a good practice that a programmer should close all the opened files before program termination .
Standard syntax for close() function
Write to a File
While doing C++ programming, you write information to a file from your program using the stream insertion operator(<<) just as you use that operator to output information to the screen. The only difference is that you use an ofstream or fstream object indeed of the cout object.
Reading from a File
You can information from a file into your program using the stream extraction operator(>>) just as you use an ifstream or fstream object instead of the cin object.