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.
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;}
fstream
to enable file operations and an fstream
object is declared.file.open()
statement by passing the file's name to be created in the parameter, along with ios::out
, which enables this file for output operations. 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.