Strange problem
I have a really weird 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 fine in my one project, but when I create a project and use these same lines of code, no test.txt file is generated. Please, what's wrong? ¨
EDIT: I expect to see test.txt in VS2008 / project_name / debug - just like the first functional project does.
a source to share
Canonical code to write to 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 do file I / O, you should check every operation, except perhaps closing a file, which is usually impossible to recover from.
As for a file created somewhere else, just give it a weird name, for example mxyzptlk.txt
, and then find it using Windows Explorer.
fstream::open()
takes two arguments: filename
and mode
. Since you do not provide the latter, you can check that the default argument fstream
is present or provide it ios_base::out
yourself.
Also, you can check if the file is open. You may not have write permissions in the current working directory (where "test.txt" will be written because you do not provide an absolute path). fstream
provides a method is_open()
as one way to test this.
Finally, consider deviating from your code. While you only have a few lines, the 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();
}
a source to share
You can use Process Monitor and filter file access and your process to determine if open / write is in progress and where on disk it is.
a source to share
There are two ways to fix this. Or do:
file.open ("test.txt", ios :: out)
#include <fstream>
using namespace std;
int main()
{
fstream file;
file.open("test.txt", ios::out);
file<<"Hello";
file.close();
}
Or you can create stream from stream instead of fstream.
#include <fstream>
using namespace std;
int main()
{
ofstream file;
file.open("test.txt");
file<<"Hello";
file.close();
}
a source to share