How do I get the directory that a program is running from?

后端 未结 23 1973
温柔的废话
温柔的废话 2020-11-22 04:39

Is there a platform-agnostic and filesystem-agnostic method to obtain the full path of the directory from where a program is running using C/C++? Not to be confused with the

23条回答
  •  南方客
    南方客 (楼主)
    2020-11-22 04:58

    If you fetch the current directory when your program first starts, then you effectively have the directory your program was started from. Store the value in a variable and refer to it later in your program. This is distinct from the directory that holds the current executable program file. It isn't necessarily the same directory; if someone runs the program from a command prompt, then the program is being run from the command prompt's current working directory even though the program file lives elsewhere.

    getcwd is a POSIX function and supported out of the box by all POSIX compliant platforms. You would not have to do anything special (apart from incliding the right headers unistd.h on Unix and direct.h on windows).

    Since you are creating a C program it will link with the default c run time library which is linked to by ALL processes in the system (specially crafted exceptions avoided) and it will include this function by default. The CRT is never considered an external library because that provides the basic standard compliant interface to the OS.

    On windows getcwd function has been deprecated in favour of _getcwd. I think you could use it in this fashion.

    #include   /* defines FILENAME_MAX */
    #ifdef WINDOWS
        #include 
        #define GetCurrentDir _getcwd
    #else
        #include 
        #define GetCurrentDir getcwd
     #endif
    
     char cCurrentPath[FILENAME_MAX];
    
     if (!GetCurrentDir(cCurrentPath, sizeof(cCurrentPath)))
         {
         return errno;
         }
    
    cCurrentPath[sizeof(cCurrentPath) - 1] = '\0'; /* not really required */
    
    printf ("The current working directory is %s", cCurrentPath);
    

提交回复
热议问题