Writing a file

I compiled a basic file "writing" program from an example in a c++ book and, while it finishes with no errors, nothing happens. The program simply completes with a returning 0. I'm new to file writing so can you point out why exactly it's not writing to the file like I expected? The book shows its result as the command prompt open, as well as poem.txt open with the string poem contained inside. I have a poem.txt located on my desktop; I assume that's where the .txt file has to be. But of course my poem.txt contains nothing.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>
#include <string>
#include <fstream>
using namespace std;

int main()
{
  string poem("\n\tI never saw a man who looked");
  poem.append("\n\tWith such a wistful eye");
  poem.append("\n\tUpon that little tent of blue");
  poem.append("Which prisoners call the sky");

  ofstream writer("poem.txt");
  if (!writer)
  {
     cout << "Error opening file for output" << endl;
     return -1;
  }

  writer << poem << endl;
  writer.close();
  cin.get();

  return 0;
}


Last edited on
I have a poem.txt located on my desktop; I assume that's where the .txt file has to be. But of course my poem.txt contains nothing.

If you don't specify the full path, the file would be located in the working directory of your program
Which file is the working directory? The main folder of the program?
Usually it's the directory of the executable file but it may change if you are using an IDE. In that case it should be the project's directory
Last edited on
Topic archived. No new replies allowed.