Opening File

hello i have a big problem with opening files can any body help me with this program

#include "iostream"
#include "fstream"
#include "conio.h"
using namespace std;
int main()
{
ofstream myfile;
myfile.open("example.txt");
myfile<<"Writing on the file";
myfile.close();
getch();
return 0;
}

in this code i expect the following output (Writing on the file)
but after i run the program the output is empty.By empty i mean nothing
and there is no errors what is the problem.
Perhaps there are no errors because you're not checking to insure the file actually opened?
1
2
3
4
5
6
7
8
...
   ofstream myfile("example.txt");
   if(!myfile)
   {
      cerr << "Failed to open the output file";
      return 1;
   }
...


And remember that the default open mode for an ofstream erases the file contents when it is opened.

Last edited on
@cpm14

I compiled and ran your program, as is, and found the file, named 'example.txt', complete with the output, "Writing on the file", in the same directory as the source code,.
what compiler do you use.
because i use Microsoft Visual Studio 2010 and it doesn't work.
@cpm14

I use Microsoft Visual Studio 2012 Express. I then use a 'CLR Console Application'. I then copied your program into MS Visual Studio 2008 Express, as a 'WIN32 Console Application', and I still get the text to save, as in the other compiler. So, I'm at a loss as to why you're having difficulties.
Please note your #includes are using the incorrect notation. You should be using the <> for system headers instead of the "".

#include <iostream>

Although this should not cause the problems you seem to be having.

because i use Microsoft Visual Studio 2010 and it doesn't work.

What do you mean by it doesn't work? Is the file created?

Topic archived. No new replies allowed.