File Creation with fail() check
Checking if file could be created after the creation object has been made along with filename parameter.
Learning Objectives
- Learning to use the fail() method of ofstream class.
Source Code
Run Output
Code Understanding
#include <iostream>
#include <fstream.h> //This header file is required for data file handling classes
using namespace std;
int main(){
ofstream fout(“/xyz/myfile.txt”);
For using creation of a file we use ofstream class (output file stream) with filename as parameter. This will try to create a file on the disk without any content (empty file) in the given directory if it exists. fout is the object name selected by us. we can give any name to this object.
if(fout.fail()) { cout<<“Unable to create file”<<endl; return -1;}
This checks the return value of fail() method of ofstream class. If it is 0 then file creation must have failed. The failure could be due to non-existence of directory, not sufficient writing permissions, disk capacity full etc. If it fails, then the control returns to operating system with error code -1 (indicated by a non zero negative value).
cout<<“File Created Successfully”<<endl;
Displays that file has been created.
fout.close();
Here we are using the close method of ofstream along with the object name prefix.
return 0;}
Notes
- This is the simplest way of creating a file with an appropriate check for file creation.
- one can also make this program using fstream class which has capability of using both in input as well as output mode.
- One can easily test the failure mode by changing the file flags to read only mode manually in the OS.
Common Errors
- It is important to give file name as string literal or a null terminated pre-initialised char array.
Suggested Filename(s): filcrech.cpp,file-create-check.cpp
CSKC| Created: 3-May-2019 | Updated: 3-May-2019|