How return a std::string from C's “getcwd” function

后端 未结 7 533
我寻月下人不归
我寻月下人不归 2021-01-20 07:35

Sorry to keep hammering on this, but I\'m trying to learn :). Is this any good? And yes, I care about memory leaks. I can\'t find a decent way of preallocating the char*, be

7条回答
  •  失恋的感觉
    2021-01-20 08:08

    How about this? It's short, exception safe, and doesn't leak.

    std::string getcwd() {
        std::string result(1024,'\0');
        while( getcwd(&result[0], result.size()) == 0) {
            if( errno != ERANGE ) {
              throw std::runtime_error(strerror(errno));
            }
            result.resize(result.size()*2);
        }   
        result.resize(result.find('\0'));
        return result;
    }
    

提交回复
热议问题