A file is used to store huge data. C++ provides multiple file management functions like file creation, opening and reading files, writing to the file, and closing a file.
Types of Files
- Text Files
- Binary Files
Text Files
These are simple text files that are saved by the (.txt) extension and can be created or modified by any text editor. Text file stores data in the form of ASCII characters and is used to store a stream of characters.
Binary Files
It is stored in binary format instead of ASCII characters. Binary files are normally used to store numeric Information (int, float, double). Here data is stored in binary form i.e, (0’s and 1’s).
File I/O 6 Step Process
Include the header file
The fstream library allows us to work with files.
To use the fstream library, include both the standard <iostream> AND the <fstream> header file:
#include <fstream>
Class | Description |
---|---|
ofstream | Creates and writes to files |
ifstream | Reads from files |
fstream | A combination of ofstream and ifstream: creates, reads, and writes to files |
Declare the file stream variables
To create a file, use either the ofstream or fstream class, and specify the name of the file.
oftream iFile; // Output file
To write to the file, use the insertion operator (<<).
Ex:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | #include <iostream> #include <fstream> using namespace std; int main() { // Create and open a text file ofstream MyFile("filename.txt"); // Write to the file MyFile << "Files can be tricky, but it is fun enough!"; // Close the file MyFile.close(); } |
Associate the file stream variables with the input/output sources
ofile . open ( ” file . txt ” ) ; // Open the output file
Check the files opened
if ( ! oFile . is_open () ) { … }
Use the file stream variables with >>, << or other input/output function
oFile >> variable/ literal / mainpulator;
Close the files
oFile. close (); // Close the output file