File Handling in C++ – Read, Write and Append Data in File

Master C++ with Real-time Projects and Kickstart Your Career Start Now!!

Program 1

// File in C++ (write a data in file)
#include<iostream>   // file
#include<fstream>   //console
using namespace std;
int main()
{
    system("cls");
    fstream fout("H://dataflair//studentdata.txt",ios::app);  //open a file in write mode
    string name;
    cout<<"Enter Name : ";
    cin>>name;
    fout<<'\n'<<name;    //write
    cout<<"File Created";
    fout.close();
    return 0;

}

Program 2

// File in C++ (read a data in file)
#include<iostream>   // file
#include<fstream>   //console
using namespace std;
int main()
{
    system("cls");
    string name; 
    fstream fin;
    fin.open("g://cppdata/student.txt",ios::in); 
    fin>>name;           // read data from file
    cout<<name;             
    fin.close();  //close
      return 0;

}

Program 3

// Copy one file into second
#include<iostream>   // file
#include<fstream>   //console
using namespace std;
int main()
{
    system("cls");
    string name;
    fstream fin("H://dataflair//studentdata.txt",ios::in);  //open a file in read mode
    fstream fout("H://dataflair//studentdata1.txt",ios::out);  //open a file in write mode
    fin>>name;   //  read data name=vivek
    fout<<name;  //  write data name=vivek
    fin.close();
    fout.close();
   cout<<"Copied successfully";
 return 0;

}

Your 15 seconds will encourage us to work even harder
Please share your happy experience on Google

courses
Image

DataFlair Team

DataFlair Team provides high-impact content on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. We make complex concepts easy to grasp, helping learners of all levels succeed in their tech careers.

Leave a Reply

Your email address will not be published. Required fields are marked *