tags:

views:

165

answers:

5

Hi, I have really strange problem. In Visual C++ express, I have very simple code, just:

#include <fstream>
using namespace std;
int main()
{
fstream file;
file.open("test.txt");
file<<"Hello";
file.close();
}

This same code works OK in my one project, but when I create now project and use this same lines of code, no file test.txt is created. Please, what is wrong?¨

EDIT: I expect to see test.txt in VS2008/project_name/debug - just like the first functional project does.

A: 

You sure you're running the right project?

Do you have both loaded in one solution? Which is the active/launched project?

Assaf Lavie
Both are active, I have actually runnig 2 instances of VC++.
noname
+2  A: 

Perhaps the executable is run in a different directory than it was before, making test.txt appear somewhere else. Try using an absolute path, such as "C:\\Users\\NoName\\Desktop\\test.txt" (The double backslashes are needed as escape characters in C strings).

Joey Adams
+2  A: 

fstream::open() takes two arguments: filename and mode. Since you are not providing the second, you may wish to check what the default argument in fstream is or provide ios_base::out yourself.

Furthermore, you may wish to check whether the file is open. It is possible that you do not have write permissions in the current working directory (where 'test.txt' will be written since you don't provide an absolute path). fstream provides the is_open() method as one way of checking this.

Lastly, think about indenting your code. While you only have a few lines there, code can soon become difficult to read without proper indentation. Sample code:

#include <fstream>
using namespace std;
int main()
{
    fstream file;
    file.open("test.txt", ios_base::out);
    if (not file.is_open())
    {
        // Your error-handling code here
    }
    file << "Hello";
    file.close();
}
Johnsyweb
+3  A: 

Canonical code to write to a file:

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

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

    if ( ! (  file << "Hello" ) ) {
       cerr << "write error\n";
    }

   file.close();

}

Whenever you perform file I/O you must test every single operation, with the possible exception of closing a file, which it is not usually possible to recover from.

As for the file being created somewhere else - simply give it a weird name like mxyzptlk.txt and then search for it using Windows explorer.

anon
+1  A: 

You can use Process Monitor and filter on file access and your process to determine whether the open/write is succeeding and where on disk it's happening.

Chris Schmich