Tuesday, March 1, 2011

simple c++ file opening issue

#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.

From stackoverflow
  • 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;
    }
    
    Robert : 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
    anon : @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++.
    wilhelmtell : you don't have to close the file. it's on the stack.
  • 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();
    
    GMan : `close()` flushes anyway.

0 comments:

Post a Comment