C++ provides file handling through stream classes such as ofstream, which can be used to create and write to files. A file can be created by opening it in output mode and checking whether the operation was successful.
- ofstream is used to create and write to a file.
- is_open() can be used to verify whether the file was opened successfully.
Example:
Input: No input is required.
Output: File created successfully.A file named Gfg.txt is created in the program's working directory.
Approach to Create a File
The file can be created by opening an ofstream object with the required filename and verifying that the file was opened successfully.
- Create an ofstream object.
- Open the file using open().
- Check whether the file was opened successfully using is_open().
- Print a success or error message accordingly.
- Close the file using close().
#include <fstream>
#include <iostream>
using namespace std;
int main()
{
// Create an ofstream object
ofstream file;
// Open the file in output mode
file.open("Gfg.txt");
// Check if the file was created successfully
if (!file.is_open())
{
cout << "Error in creating file!";
return 1;
}
cout << "File created successfully.";
// Close the file
file.close();
return 0;
}
Output
File created successfully.
Explanation: The ofstream object opens Gfg.txt in output mode. If the file does not exist, it is created. The is_open() function verifies whether the file was opened successfully.