tags:

views:

55

answers:

2
#include <iostream>
#include <fstream>
using namespace std;

int main ()
{
  ofstream testfile;
  testfile.open ("test.txt");
  testfile << "success!\n";
  testfile.close();
  return 0;
}

1)called "g++ testfile.cpp"
2)created "test.txt"
3)called "chmod u+x a.out"
4)???
5)file remains blank.

I feel like an idiot for failing at something as trivial as this is supposed to be.

+5  A: 

When performing file I/O, you almost always need to test for errors:

#include <iostream>
#include <fstream>
using namespace std;

int main ()
{
  ofstream testfile;
  testfile.open ("test.txt");
  if ( ! testfile.is_open() ) {
     cerr << "file open failed\n";
     return 1;
  }

  if ( ! testfile << "success!\n" ) {
     cerr << "write failed\b";
     return 1;
  }

  testfile.close();   // failure unlikely!
  return 0;
}
anon
1) use "(!( testfile << "success!\n" ))" not (! testfile << "success!\n" )still does nothing.I also tried adding "cout<<"something";" at the start of the main function.I am beginning to believe the problem is not in the executable syntax
Robert
@Robert Good catch. I think your problem is to do with your environment, or your understanding of it, and not with your understanding of C++.
anon
you don't have to close the file. it's on the stack.
wilhelmtell
A: 

In theory they're equivalent, but just to make sure, do try << endl instead of "\n" to flush the stream.

ofstream testfile;
testfile.open ("test.txt");
testfile << "success!" << endl;
testfile.close();
clyfe
`close()` flushes anyway.
GMan