C++ Files

C++ Files


C++ Files 
A file is a location or information, usually stored on a computer’s disk. Information can be saved to files and then later reused.
File Names-
  • All files are assigned a name that is used for identification purposes by the operating system and the user.
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:
Example
#include <iostream>
#include <fstream>
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.
Starting Out with C++ 1 Chapter 12: File Operations What is a File? A file  is a collection on information, usually stored on some electronic medium.  Information. - ppt download
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
       opening mode
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 
                void close()  
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.
Example
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.
 Example  
Output