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. Follow the below steps:
- Declare an
ofstream
object namedfile
for output file operations. - Use
file.open("fileName")
to create and open a file in write mode. - Verify if the file was successfully opened using
file.is_open()
.- If the file wasn't created, output an error message and return a non-zero value.
- If the file opens successfully, print "File created successfully."
- Use
file.close()
to close the file and free up system resources.
Below is the program to create a file:
#include <fstream>
#include <iostream>
using namespace std;
int main(){
//using ofstream for output file operations.
ofstream file;
// Opening file "Gfg.txt" in write mode.
file.open("Gfg.txt");
// Check if the file was successfully created.
if (!file.is_open())
{
cout << "Error in creating file!" << endl;
// Return a non-zero value to indicate an error.
return 1;
}
cout << "File created successfully." << endl;
// Close the file to free up resources.
file.close();
return 0;
}
Output
File created successfully. //File named Gfg.txt is created