TheCatfishMaw February 2016

C++ will not create a file to output text to? [SOLVED]

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();

Answers


Radek February 2016

Nice! ofstream::good() returns true if no error occurs. Use a negation in the if-condition.

if (!file_writer.good()) {
...
}


Thomas Symalla February 2016

Check your fail() error message:

if (outfile.fail())
    cout << strerror(errno) << endl;


GTKM February 2016

You cannot write to "C:". Try with a different path, and it should work.


Chris February 2016

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();

Post Status

Asked in February 2016
Viewed 3,937 times
Voted 5
Answered 4 times

Search




Leave an answer