简体   繁体   中英

c++ - _mkdir giving false errors windows

Hi I am trying to make a directory in windows with this code

header

#include <direct.h>

script

int main() {
    string local = "C:/Program Files (x86)/Mail";   

    try
    {
        _mkdir (local.c_str ());
        cout << "It is made?";
    }

    catch(invalid_argument& e)
    {
        cout << e.what () << " " << (char*) EEXIST;
        if (e.what () == (char*) EEXIST) {
            cout << e.what () << " " << (char*) EEXIST;
        }
        return;
    }
}

The file is clearly not made, but it is also not making the error it should.

_mkdir won't throw an exception. (This is not python or boost, or any smart middleware)

Read the documentation you were referring to: it returns a value. 0 is OK, -1: error, ask why to errno

Don't ignore the return value. You probably have insufficient rights without UAC elevation to create the directory.

So I finally figured errno out, which for errno you need the header(atleast on windows) < errno.h>. The complete list of errno codes .

If you want to see what errno code something is throughing lets say

if (
    _mkdir(((string)"C:/Program Files (x86)/Mail").c_str()) == 0 ||
    errno == 17 /* this is the code for - File exists - */
){
    // Do stuff

} else {
    int errorCode = errno; // You need to save the code before anything else,
                           //    becuase something else might change its value
    cout << errorCode;
}

This works in windows, I am not sure if there is a library to use that is portable for both(If anyone knows please share).

Not Important/rant -

The one thing I have noticed with Linux documentation/user explanations of these thing is that everything is made to complex. I mean yes we all are impressed with your knowledge of words no one but computer science majors know, but there clearly are easier ways to explain things, Like freecodecamp does, or kahn academy.

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