How to Open a File Using Constructor in C++

Free C++ course with real-time projects Start Now!!

Program 1

// open file using constructor
#include<iostream>
#include<fstream>
#define clrscr() system("cls")
using namespace std;
int main()
{
    char name1[50];
    clrscr();
      fstream fout("f://cppfile/City.txt",ios::app);  //using constructor
//     cout<<"Enter Name of City: ";
//     cin>>name;
//     fout<<name;
//     fout.close();
//     cout<<"\n File Created........";
//     return 0;
}

Program 2

// open file using constructor for read mode
#include<iostream>
#include<fstream>
#define clrscr() system("cls")
using namespace std;
int main()
{
    clrscr();
    fstream fin("d://dataflair/Student.txt",ios::in);
    char name[50];
    fin>>name;
    cout<<name;
    fin.close();
}

Program 3

// file copy
#include<iostream>
#include<fstream>
#define clrscr() system("cls")
using namespace std;
int main()
{
    char name[50];
    clrscr();
    fstream fin("F://cppfile/student.txt",ios::in);
    fstream fout("F://cppfile/student1.txt",ios::app);
    fin>>name;
    fout<<name;
    cout<<"Copied Success";
    return 0;

}

Program 4

// merge file 
#include<iostream>
#include<fstream>
#define clrscr() system("cls")
using namespace std;
int main()
{
    char temp[50];
    fstream fin1("f://cppfile/student.txt",ios::in);
    fstream fin2("f://cppfile/city.txt",ios::in);
    fstream fout("f://cppfile/info.txt",ios::app);
    //Read data from student file and write in info file
    fin1>>temp;
    fout<<temp;
    fin1.close();
    //Read data from city file and write in info file
    fin2>>temp;
    fout<<temp;
    fin2.close();
    fout.close();
    cout<<"Mere two file";
    return 0;

}

 

We work very hard to provide you quality material
Could you take 15 seconds and share your happy experience on Google

follow dataflair on YouTube

Leave a Reply

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