What is a cross-platform way to get the current directory?

前端 未结 3 1453
孤街浪徒
孤街浪徒 2020-12-05 23:55

I need a cross-platform way to get the current working directory (yes, getcwd does what I want). I thought this might do the trick:

#ifdef _WIN32
    #includ         


        
3条回答
  •  粉色の甜心
    2020-12-06 00:32

    Calling getcwd with a NULL pointer is implementation defined. It often does the allocation for you with malloc (in which case your code does have a memory leak). However, it isn't guaranteed to work at all. So you should allocate your own buffer.

    char *cwd_buffer = malloc(sizeof(char) * max_path_len);
    char *cwd_result = getcwd(cwd_buffer, max_path_len);
    

    The Open Group has an example showing how to get the max path length from _PC_PATH_MAX. You could consider using MAX_PATH on Windows. See this question for caveats to this number on both platforms.

提交回复
热议问题