How to create a file using a C++ program
Overview
In C++, we use files to read and write data. In addition to this, files can also be created through C++.
C++ uses the fstream library to carry out file operations.
Code
We'll write a C++ program to create a file:
#include <iostream>//include fstream for file oprations#include <fstream>using namespace std;int main(){fstream file; //object of fstream class//open file "test.txt" in out(write) mode// ios::out Open for output operations.file.open("test.txt",ios::out);//If file is not created, return errorif(!file){cout<<"Error in file creation!";return 0;}else{ //File is createdcout<<"File Creation successfull.";}//closing the filefile.close();return 0;}
Explanation
- Lines 1 to 8: We include
fstreamto enable file operations and anfstreamobject is declared. - Line 13: We create a file in the
file.open()statement by passing the file's name to be created in the parameter, along withios::out, which enables this file for output operations. - Lines 16 to 24: We check whether the file creation is successful or not, and it returns the output accordingly.
- Line 26: We use
file.close()to close the file. This is important to prevent data loss.
Note: The file won't be created if the file is opened in input mode. It is only created if the file is opened in either output mode or append mode.