C++ program to create a file

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.
   // If no file is created, then
   // show the error message.
       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.
   return 0;



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.