Creating files in C++

Uffo picture Uffo · Jan 25, 2009 · Viewed 293.9k times · Source

I want to create a file using C++, but I have no idea how to do it. For example I want to create a text file named Hello.txt.

Can anyone help me?

Answer

James Thompson picture James Thompson · Jan 25, 2009

One way to do this is to create an instance of the ofstream class, and use it to write to your file. Here's a link to a website that has some example code, and some more information about the standard tools available with most implementations of C++:

ofstream reference

For completeness, here's some example code:

// using ofstream constructors.
#include <iostream>
#include <fstream>  

std::ofstream outfile ("test.txt");

outfile << "my text here!" << std::endl;

outfile.close();

You want to use std::endl to end your lines. An alternative is using '\n' character. These two things are different, std::endl flushes the buffer and writes your output immediately while '\n' allows the outfile to put all of your output into a buffer and maybe write it later.