File Handling

File Handling allows you to work with files. Using file handling, you can write into files and you can also read from files. You need to include fstream header file to work with files.

Note: Whenever you use file handling in code, a file is created and any input user enters saves in the file.


Writing to a file:

To write data to a file you can use ofstream class from fstream header file. Use .open() function to create an object and open a file.

#include <fstream>
  using namespace std;

int main() {
  ofstream outputFile("output.txt"); 

  if (outputFile.is_open()) {
    outputFile<<"Write this to the file." << endl;
    outputFile<<42<< " is an integer." << endl;
    outputFile.close();
    cout << "Written successfully." << endl;
  } else {
    cout << "Error opening the file." << endl;
  }

  return 0;
}

Reading from a file:

To read data from a file you can use ifstream class from fstream header file. Use .open() function to create an object and open a file.

#include <fstream>
#include <string>
using namespace std;

int main() {
    ifstream inputFile("input.txt");

    if (inputFile.is_open()) {
        string line;
        while (getline(inputFile, line)) {
            cout << line << endl;
        }
        inputFile.close();
    } else {
        cout << "Error opening the file." << endl;
    }

    return 0;
}

Appending to a file:

To append data to an existing file you can use ofstream class with append function. Use .open() function to create an object and open a file.

#include <fstream>
  using namespace std;

int main() {
    ofstream outputFile("output.txt", ios::app);

    if (outputFile.is_open()) {
        outputFile << "Appended to the file." << endl;
        outputFile.close();
        cout << "Appended successfully." << endl;
    } else {
        cout << "Error opening the file." << endl;
    }

    return 0;
}

In the following code, we are creating a file, and when we execute the program a file is created in the directory where your program is located. When you give input, the input will be saved in that file.

file.cpp
#include <iostream>
#include<fstream>  

using namespace std;
int main()
{
	int num;
	cout<<"Enter a number\n";
	cin>>num;
	fstream txt;
		txt.open("inp.txt", ios::out);
		txt << "Number: ";
		
		txt<<num;
		
		txt.close();
}