简体   繁体   中英

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");
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM