- C++ Introduction
- C++ Getting Started
- C++ Syntax
- C++ Output (Print Text)
- C++ Comments
- C++ Variables
- C++ Declare Multiple Variables
- C++ Identifiers
- C++ User Input
- C++ Data Types
- C++ Operators
- C++ Strings
- C++ Math
- C++ Booleans
- C++ Conditions
- C++ Switch
- C++ While Loop
- C++ For Loop
- C++ Break And Continue
- C++ Arrays
- C++ References
- C++ Pointers
- C++ Functions
- C++ Function Overloading
- C++ OOP
- C++ Classes And Objects
- C++ Class Methods
- C++ Constructors
- C++ Access Specifiers
- C++ Encapsulation
- C++ Inheritance
- C++ Multilevel Inheritance
- C++ Multiple Inheritance
- C++ Inheritance Access
- C++ Polymorphism
- C++ Files
- C++ Exceptions
- C++ How To Add Two Numbers
C++ Files
C++ Files
The fstream
library allows us to work with files.
To use the fstream
library, include both the standard <iostream>
AND the <fstream>
header file:
Example
#include <fstream>
There are three classes included in the fstream
library, which are used to create, write or read files:
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 |
Practice Excercise Practice now
Create And Write To A File
To create a file, use either the ofstream
or fstream
class, and specify the name of the file.
To write to the file, use the insertion operator (<<
).
Example
#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();
}
Why do we close the file?
It is considered good practice, and it can clean up unnecessary memory space.
Practice Excercise Practice now
Read A File
To read from a file, use either the ifstream
or fstream
class, and the name of the file.
Note that we also use a while
loop together with the getline()
function (which belongs to the ifstream
class) to read the file line by line, and to print the content of the file:
Example
string myText;
// Read from the text file
ifstream MyReadFile("filename.txt");
// Use a while loop together with the getline() function to read the file line by line
while (getline (MyReadFile, myText)) {
// Output the text from the file
cout << myText;
}
// Close the file
MyReadFile.close();
Practice Excercise Practice now
Products
Partner
Copyright © RVR Innovations LLP 2024 | All rights reserved - Mytat.co is the venture of RVR Innovations LLP