How to Open and Close a File in C++

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

Program 1

// open file using Open Method for read
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main()
{
    fstream fout;
    system("cls");
    fout.open("H://dataflair//studentname.txt",ios::app);  //open a file in write mode)
    fout<<"Vishal Verma";
    fout.close();

    fout.open("H://dataflair//studentcourse.txt",ios::app);  //open a file in write mode)
    fout<<"MCA";
    fout.close();

    fout.open("H://dataflair//studentcity.txt",ios::app);  //open a file in write mode)
    fout<<"Indore";
    fout.close();
   cout<<"3 File Created......";
    return 0;
}

Program 2

// open file using Open Method for read
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main()
{
    fstream fin;
    string str;
    system("cls");
    fin.open("H://dataflair//studentname.txt",ios::in);  //open a file in read mode)
    fin>>str;
    cout<<" Name: "<<str<<endl;
    fin.close();

    fin.open("H://dataflair//studentcourse.txt",ios::in);  //open a file in read mode)
    fin>>str;
    cout<<" Course: "<<str<<endl;
    fin.close();
    
    fin.open("H://dataflair//studentcity.txt",ios::in);  //open a file in read mode)
    fin>>str;
    cout<<"City: "<<str<<endl;

    fin.close();
   
    return 0;
}

 

Did you like our efforts? If Yes, please give DataFlair 5 Stars 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 *