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

后端 未结 7 521
我寻月下人不归
我寻月下人不归 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:18

    This will work on Windows and Linux, since they both support the automatic allocation behavior when the buf argument to getcwd is NULL. However, be aware that this behavior is not standard, so you may have issues on more esoteric platforms.

    You can do it without relying on this behavior, though:

    const string getcwd()
    {
        size_t buf_size = 1024;
        char* buf = NULL;
        char* r_buf;
    
        do {
          buf = static_cast<char*>(realloc(buf, buf_size));
          r_buf = getcwd(buf, buf_size);
          if (!r_buf) {
            if (errno == ERANGE) {
              buf_size *= 2;
            } else {
              free(buf);
              throw std::runtime_error(); 
              // Or some other error handling code
            }
          }
        } while (!r_buf);
    
        string str(buf);
        free(buf);
        return str;
    }
    

    The above code starts with a buffer size of 1024, and then, if getcwd complains that the buffer is too small, it doubles the size and tries again, and repeats until it has a large enough buffer and succeeds.

    Note that calling realloc with its first argument as NULL is identical to malloc.

    0 讨论(0)
提交回复
热议问题