bg9848
bg9848

Reputation: 322

C++ ofstream will not open file

I cannot open a file with ostream. The file will create. When I check the perms for the file the file does not have modify permission but it has write/read perm. Not sure if that means anything.

#include <iostream>
#include <fstream>

void writeFile(string name) {
    ofstream myfile(name.c_str()); // create file
    myfile.open(name.c_str(), ios::app);
    if (myfile) {
    myfile << "a \n";
    } else {
        cout << "failed to open\n";
    }
    myfile.close();
}

int main() {
writeFile("output.txt");
}

Upvotes: 0

Views: 3114

Answers (1)

user2100815
user2100815

Reputation:

This:

 ofstream myfile(name.c_str());

opens the file. Then this:

 myfile.open(name.c_str(), ios::app);

attempts to open it again. You want:

 ofstream myfile(name.c_str(), ios::app );      

and forget the call to open().

Upvotes: 4

Related Questions