Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

c++
file handling
fstream
communitycreator

How to create a file using a C++ program

Saad Akbar

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 error
  if(!file){
    cout<<"Error in file creation!";
    return 0;
  }else{ //File is created
    cout<<"File Creation successfull.";
  }
  //closing the file
  file.close();
    
  return 0;
}
The program to create a file

Explanation

  • Lines 1 to 8: We include fstream to enable file operations and an fstream object 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 with ios::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.

RELATED TAGS

c++
file handling
fstream
communitycreator
RELATED COURSES

View all Courses

Keep Exploring