fstream

I'm having a bit of trouble with making a text file. Can anyone identify the problem?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include "stdafx.h"
#include <iostream>
#include <fstream>
using std::cout;
using std::cin;


int main ()
{
	std::ofstream myfile;
	myfile.open("example.txt");
	myfile << "This will show up the file.\n";
	myfile.close();


	return 0;
}


When I output this, a file isn't created, am I doing something horribly wrong?
That works for me, although I'm on Linux/g++

Try

myfile.flush();

before the close perhaps?
Closing the file should come with a flush, that shouldn't the problem. Are you sure you are looking in the right directory for the file?
I don't know how I could change the directory.

I don't know how to get the file either (It doesn't seem to be there even with myfile.flush())
Where do you actually look for your file? I mean, the file might be created after all, you may just look for it in the wrong place.
You may try checking to see if the file was opened correctly...

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
#include <fstream>
using std::cout;
using std::cin;


int main ()
{
	std::ofstream myfile;
	myfile.open("example.txt", std::ofstream::out | std::ofstream::trunc);
	if (myfile.fail())
		cout << "Unable to open file" << std::endl;
	myfile << "This will show up the file.\n";
	myfile.close();

	return 0;
}
That last one fixed it.
Thank you, JMJAtlanta!
Topic archived. No new replies allowed.