Changing the current directory in Linux using C++

前端 未结 3 670
余生分开走
余生分开走 2021-01-02 16:29

I have the following code:

#include 
#include 
#include 

using namespace std;

int main()
{
    // Variables
          


        
3条回答
  •  失恋的感觉
    2021-01-02 17:06

    int chdir(sDirectory); isn't the correct syntax to call the chdir function. It is a declaration of an int called chdir with an invalid string initializer (`sDirectory).

    To call the function you just have to do:

    chdir(sDirectory.c_str());
    

    Note that chdir takes a const char*, not a std::string so you have to use .c_str().

    If you want to preserve the return value you can declare an integer and use a chdir call to initialize it but you have to give the int a name:

    int chdir_return_value = chdir(sDirectory.c_str());
    

    Finally, note that in most operating system the current or working directory can only be set for the process itself and any children it creates. It (almost) never affects the process that spawned the process changing its current directory.

    If you expect to find the working directory of your shell to be changed once your program terminates you are likely to be disappointed.

提交回复
热议问题