> For the complete documentation index, see [llms.txt](https://mr-poston-1.gitbook.io/c++/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://mr-poston-1.gitbook.io/c++/2.-going-beyond-the-basics/2.4-file-input-output/2.4.4-writing-to-a-file.md).

# 2.4.4 Writing to a File

Just like reading in from a file is similar to reading in from the console, writing to a file is similar to writing to the console. To output to a file, you will open a file as an output file stream and then stream into the file the same way you would stream to the console.

### Creating the Output File Stream

As mentioned earlier in the lesson, the `fstream` library is used for both input and output files. To output to a file, you will first include the `fstream` library.

```
#include <fstream>
```

As you did with file input, you are going to create an output file stream variable and then open the file name that you want. If the file does not already exist, it will be created. If it does exist, it will be overwritten.

```
ofstream out;
out.open("output.txt");
```

### Streaming To the Output File

Once the output file stream has been created, streaming to the file is the same as streaming to the console, just replacing `cout` with the output file stream. For example, if you use the `out` variable created above, you can stream `Hello World` to the file like this:

```
out << "Hello World" << endl;
```

When you are finished with your output, you can close the file using the close function.

```
out.close();
```

### [Try This Example](https://replit.com/@Poston/244-Writing-to-a-File#main.cpp)
