File Handling in C++
File handling means reading data from a file and manipulating the data of a file.
File Handling Operations in C++
1. Open a file
We can use open() member function of ofstream class to open a file.
2. Read a file
We can use getline() member function of ifstream class to read a file.
3. Write to a file
We can use << operator to write to a file after opening a file with the object of ofstream class.
Example
C++
#include <fstream> #include <iostream> #include <string> using namespace std; int main() { ofstream outputFile( "example.txt" ); // Open the file for writing outputFile.open( "example.txt" ); if (outputFile.is_open()) { // Write data to the file outputFile << "Hello, World!" << endl; outputFile << 42 << endl; outputFile.close(); // Close the file } else { // Failed to open the file cout << "Error opening the file for writing." << endl; return 1; } // Reading from a file ifstream inputFile( "example.txt" ); if (inputFile.is_open()) { string line; while (getline(inputFile, line)) { // Print each line cout << line << endl; } // Close the file inputFile.close(); } else { // Failed to open the file cout << "Error opening the file for reading." << endl; return 1; } return 0; } |
This C++ cheat sheet can serve as a reference guide for programmers that provides quick access to concepts of C++.
C++ Cheatsheet
This is a C++ programming cheat sheet. It is useful for beginners and intermediates looking to learn or revise the concepts of C++ programming. While learning a new language, it feels annoying to switch pages and find different websites for different concepts that are easily understandable. You can learn C++ concepts very easily using this cheat sheet.
C++ is a high-level programming language. It was developed in 1983 by Bjarne Stroustrup at Bell Labs. It is used for developing various applications.
Contact Us