Skip to main content

C++: 9. File Handling

Files are used to store data in a storage device permanently. File handling provides a mechanism to store the output of a program in a file and perform various operations on it.

Example of opening/creating a file
  #include<iostream>
  #include<fstream>
  using namespace std;
  int main()
  {
  fstream new_file; 
  new_file.open("new_file",ios::out);  
  if(!new_file) 
  {
  cout<<"File creation failed";
  }
  else
  {
  cout<<"New file created";
  new_file.close(); // Step 4: Closing file
  }
  return 0;
  }
	
Writing to a File
  #include <iostream>
  #include <fstream>
  using namespace std;
  int main()
  {
  fstream new_file; 
  new_file.open("new_file_write.txt",ios::out);  
  if(!new_file) 
  {
  cout<<"File creation failed";
  }
  else
  {
  cout<<"New file created";
  new_file<<"Learning File handling";    //Writing to file
  new_file.close(); 
  }   
  return 0;
  }
      
Reading from a File
  #include <iostream>
  #include <fstream>
  using namespace std;
  int main()
  {
  fstream new_file; 
  new_file.open("new_file_write.txt",ios::in);   
  if(!new_file) 
  cout<<"No such file"; } else { char ch; while (!new_file.eof()) { new_file >>ch; 
  cout << ch;   
  }
  new_file.close();    
  return 0;
  }      
    

Comments