How to create a file

This is probably a very simple problem. I need to create a new file called testfile.txt. I have tried doing this:

1
2
3
4
5
6
7
8
#include <iostream>
#include <fstream>

int main()
{
std::fstream afile("testfile.txt");
}


The problem is that this code does not create testfile.txt. What am I doing wrong?
Add the out flag
 
std::fstream afile("testfile.txt", std::ios::out);

or use ofstream
 
std::ofstream afile("testfile.txt");
ok - thanks
It may be common sense, but since you asked I thought I would add, the command your using is to read a file.

The command Peter87 gave you is to write a file.

You only create files on a Write operation.
I understand that std::fstream afile creates a file stream that can be read and written to. I'm not sure I understand what you mean?
closed account (j3Rz8vqX)
http://www.cplusplus.com/doc/tutorial/files/

With fstream, you have the option of both "ios::in" which is input reading from file, and "ios::out" which is output writing to file.

ofstream would be the alternative to writing to file, and ifstream would be the alternative to reading from file.

Options are provided in the link above.
The following link is to a class handout at the University of Michigan explaining filestreams clearly and is very easy to understand.

It helped me a bunch so I hope it can help you as well.

http://www.umich.edu/~eecs381/handouts/filestreams.pdf
@Stoneynine - thanks
Topic archived. No new replies allowed.