C++ program to create a file and write data to it

Introduction :

In this C++ tutorial, we will learn how to create one file and how to write content to it. C++ provides one library called ifstream for file related IO operations. We will use it to open one file and write content to it.

C++ example program :

We need to do the following steps to write content to a file :

  • Open the file
  • Write content
  • Close the file

If I write the above steps in code, it looks as like below :

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

int main()
{
    ofstream file("myfile.txt");
    string text = "The quick brown fox jumps over the lazy dog";

    file << text << endl;

    file.close();

    return 0;
}

It opens a file with name myfile.txt in the same folder and write the string text to it. Finally, we are closing the file. We can also write the same program as like below :

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

int main()
{
    ofstream file;
    file.open("myfile.txt");

    string text = "The quick brown fox jumps over the lazy dog";

    file << text << endl;

    file.close();

    return 0;
}