Advertisement

File Handling in C++

 What is File handling in C++ ??

File handling

File handling is work like backend in easy way file handling can store the data in another file which is "sample.txt", dat, and much more this is the type how you can save the file.

When you learning or beginner in any programming language you can't store your data into the database reason is if you are beginner and store data direct into data base knowing his knowledge so you may be destroy the data base.

So, file handling is work like data base where you can save your data permanently and see when your need. 

There is a example how you can work with file handling so, take the code and run in your PC.

Example  :

/*
file handling in C++
    If we can do any type of work with files first use <fstream>
header file.
    this file can take 3 classes.
    1. ofstream = which is used for creating and writing a file.
    2. istream = that is used for reading the file.
    3. fstream = It is used for perform both the operations.

let's start
*/

#include<iostream>
#include<fstream>
using namespace std;
int main()
{
    // this is for creating and writing in a file.
    // char name[20]; // char takes 1 bytes so we make array.

    // ofstream out("tesr.txt"); //out is the function of ofstream.
    // // txt is a file which i used as a backend.
    // cout<<"Enter the name \n";
    // cin.getline(name,20);
    // out<<"Name : "<<name;

    // this is the method of writing in a file
    // Now we see that how to read file.
    // This is for reading the file.    
    string file;
    // here we can use the fstream to read the file.
    fstream in("tesr.txt"); // in is a function of fstream.
    while (getline(in,file))
    {
        cout<<file;
    }

    // we use string bcoz string can show all the spaces and
    // all the data which i have stored in text file.
    return 0;
}

If you can do any work with file handling firstly we use the <fstream>  header file.

This file can take the three classes.

  1. ofstream 
  2. ifstream 
  3. fstream 

  • Ofstream : It is used for Creating and Writing the File.
  • Ifstream : It is used for Reading the File.
  • Fstream : It is used to perform all the operation.

When we use ofstream then we use the out function to create a file and writing in a  file. there are many ways to use ofstream.

Use of ifstream is to read the the file.

For more understanding See this video : File handling


Post a Comment

0 Comments