Search code examples
c++macosg++fopen

fopen("filename", "wb") returns null


Code like this:

#include <iostream>

using namespace std;
int main(){
    FILE* to = NULL; 
    to = fopen("cpp", "wb");
    if(to != NULL)
        cout << 1 << endl ;
    cout << 2 << endl;
}

compile with g++ with option -o,then run.Returns "2".To see cpp folder with ls -al :drwxr-xr-x 2 anyone staff 64 6 8 08:31 cpp

Why it returns "2".Why I cannot open the folder for write?


Solution

  • This happens because you are trying to open a folder for writing. According to fopen documentation, you get [EISDIR] error:

    [EISDIR]
    The named file is a directory and mode requires write access.

    You can tell what error you get by printing strerror(errno)):

    cout << strerror(errno)) << endl;