Is there a C++ equivalent to getcwd?

2019-01-18 08:58发布

I see C's getcwd via: man 3 cwd

I suspect C++ has a similar one, that could return me a std::string .

If so, what is it called, and where can I find it's documentation?

Thanks!

标签: c++ getcwd
8条回答
Lonely孤独者°
2楼-- · 2019-01-18 09:34

Let's try and rewrite this simple C call as C++:

std::string get_working_path()
{
    char temp [ PATH_MAX ];

    if ( getcwd(temp, PATH_MAX) != 0) 
        return std::string ( temp );

    int error = errno;

    switch ( error ) {
        // EINVAL can't happen - size argument > 0

        // PATH_MAX includes the terminating nul, 
        // so ERANGE should not be returned

        case EACCES:
            throw std::runtime_error("Access denied");

        case ENOMEM:
            // I'm not sure whether this can happen or not 
            throw std::runtime_error("Insufficient storage");

        default: {
            std::ostringstream str;
            str << "Unrecognised error" << error;
            throw std::runtime_error(str.str());
        }
    }
}

The thing is, when wrapping a library function in another function you have to assume that all the functionality should be exposed, because a library does not know what will be calling it. So you have to handle the error cases rather than just swallowing them or hoping they won't happen.

It's usually better to let the client code just call the library function, and deal with the error at that point - the client code probably doesn't care why the error occurred, and so only has to handle the pass/fail case, rather than all the error codes.

查看更多
祖国的老花朵
3楼-- · 2019-01-18 09:35

I used getcwd() in C in the following way:

char * cwd;
cwd = (char*) malloc( FILENAME_MAX * sizeof(char) );
getcwd(cwd,FILENAME_MAX);

The header file needed is stdio.h. When I use C compiler, it works perfect.

If I compile exactly the same code using C++ compiler, it reports the following error message:

identifier "getcwd" is undefined

Then I included unistd.h and compiled with C++ compiler. This time, everything works. When I switched back to the C compiler, it still works!

As long as you include both stdio.h and unistd.h, the above code works for C AND C++ compilers.

查看更多
登录 后发表回答