info@tutsfinder.in



Files and Streams


In this tutorial we will learn how to read and write from a file. In C++ there is a library called fstream that defines some data types –

Ofstream – it is used to create files and performs wrting operation on it, it performs outpur operations.

Ifstream – it is used for reading from the files, it performs input operations.

Fstream – It can perform functions of both ofstream and ifstream which means it can read and write from the files.


Operations in file –

• Creating a file: open()

• Reading data: read()

• Writing new data: write()

• Closing a file: close()


Create and opening a file –



#include <iostream>
#include <fstream>

using namespace std;

int main()
{
    fstream fs; 
    fs.open("C:\xyz.txt",ios::out);  // Creating new file
    if(!fs) 
    {
        cout<<"File creation failed";
    }
    else
    {
        cout<<"New file created";
        fs.close();
    }
    
    return 0;
}


Output:

New file created


Reading from a file –



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

int main () {  
  string str;  
  ifstream filestream("xyz.txt");  
  if (filestream.is_open())  
  {  
    while ( getline (filestream,str) )  
    {  
      cout << str <<endl;  
    }  
    filestream.close();  
  }  
  else {  
      cout << "File opening is fail !"<<endl;   
    }  
  return 0;  
}


Writing to a file –



#include <iostream>
#include <fstream>

using namespace std;

int main()
{
    fstream fs; 
    fs.open("C:\xyz.txt",ios::out);  
    if(!fs) 
    {
        cout<<"File creation failed";
    }
    else
    {
        cout<<"New file created successfully";
        fs<<"TutsFinder";    
        fs.close(); 
    }
  
    return 0;
}