Skip to content
Related Articles

Related Articles

Improve Article

C++ program to create a file

  • Difficulty Level : Medium
  • Last Updated : 28 Sep, 2018
Geek Week

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."Gfg.txt",ios::out);
   // 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;


Want to learn from the best curated videos and practice problems, check out the C++ Foundation Course for Basic to Advanced C++ and C++ STL Course for the language and STL. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
My Personal Notes arrow_drop_up
Recommended Articles
Page :