So, what I have here is a simple snippet of C++ code that merely askes for a filepath, checks if the filepath exists, and if it does, the program closes. If it doesn't, it creates a file and writes text to it. The path I enter is C:\temp.txt, but no matter which path I use the result is the same: No file is created. I am using Visual Studio 2010.
string outFile = "";cout << "Enter a file path for an output file that does not exist already: ";
cin >> outFile;
ofstream file_writer;
file_writer.open(outFile, ios_base::out | ios_base::in);
if (!file_writer.fail()) {
cout << "This file exists already!" << endl;
cout << strerror(errno) << endl;
system("PAUSE");
return 255;
}
file_writer << "Hello!";
file_writer.close();
You could try:
string outFile = "";
cout << "Enter a file path for an output file that does not exist already: ";
cin >> outFile;
ofstream file_writer;
file_writer.open(outFile, ios::in);
if (file_writer.good()) { //This now just checks if the file exists already
cout << "This file exists already!" << endl;
system("PAUSE");
return 255;
}
file_writer.open(outFile, ios::out); //Now since we know the file doesn't exist, we can create it safely
if (!file_writer.good()) {
cout << "Failed to create file!" << endl;
return 254;
}
file_writer << "Hello";
file_writer.close();
Check your fail() error message:
if (outfile.fail())
cout << strerror(errno) << endl;
You cannot write to "C:". Try with a different path, and it should work.
Nice! ofstream::good()
returns true if no error occurs. Use a negation in the if-condition.
if (!file_writer.good()) {
...
}