• Register
100 points
7 4

In this article we will discuss and write a program to create a text file in the first place and then the program will write in the file by itself. To create a program like this we have to use fstream. 

The program will create a text file and if the file is created then it will show “file created successfully” otherwise it shows “Error in creating file!!!”.

Approach

Declare fstream file class and open the text file in writing mode. Program will look for the file in the current directory if the file is not present then it creates a new text file. Then it will add text or data into the file. After that we have to close the file.

To write data into the file we can use ofstream or fstream.
Ofstream: ofstream is a data type that represents the output file steam and is used to create files and to write data into the files.

Fstream: this data type represents the file stream, and it has abilities of ofstream and ifstream. So it can read, write and create files.

Program

Using ofstream
#include <iostream>
#include <fstream>
using namespace std;

int main()
{
	ofstream MyFile("here.txt");
	MyFile << "here is some text";
	MyFile.close();
	return 0;
}

Using fstream

#include <bits/stdc++.h> 
using namespace std; 
  
// Driver code 
int main() 
{ 
   
   fstream file; 
  
  
   file.open("newfile.txt",ios::out); 
  
   // If no file is created, then 
   // show the error message. 
   if(!file) 
   { 
       cout<<"Error in creating file!!!"; 
       return 0; 
   } 
  
   cout<<"File created successfully."; 

   file << "here is some text" << endl;

   file.close();

   return 0;
}

 

Output

Both of the above code will create text files and enter the “here is some code in the file”.
 
hope this will help.
 
100 points
7 4