Open In App

C++ program to create a file

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

Problem Statement: Write a C++ program to create a file using file handling and check whether the file is created successfully or not. If a file is created successfully then it should print “File Created Successfully” otherwise should print some error message.

Approach: Declare a stream class file and open that text file in writing mode. If the file is not present then it creates a new text file. Now check if the file does not exist or not created then return false otherwise return true.

Below is the program to create a file:




// C++ implementation to create a file
#include <bits/stdc++.h>
using namespace std;
  
// Driver code
int main()
{
    // fstream is Stream class to both
    // read and write from/to files.
    // file is object of fstream class
   fstream file;
  
   // opening file "Gfg.txt"
   // in out(write) mode
   // ios::out Open for output operations.
   file.open("Gfg.txt",ios::out);
  
   // If no file is created, then
   // show the error message.
   if(!file)
   {
       cout<<"Error in creating file!!!";
       return 0;
   }
  
   cout<<"File created successfully.";
  
   // closing the file.
   // The reason you need to call close()
   // at the end of the loop is that trying
   // to open a new file without closing the
   // first file will fail.
   file.close();
  
   return 0;
}


Output:
img


Last Updated : 28 Sep, 2018
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads