Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot change directory using system() in C++ [duplicate]

Tags:

c++

cmd

cd

system

As the title says, I cannot use "cd" in even a super simple C++ program. More accurately, I CAN use it (i.e. it compiles and doesn't throw any errors) but it carries on as if I haven't.

My code is as follows:

#include <iostream>
#include <cstdlib>

int main()
{
    system("cd");
    system("dir");

    system("cd C:\\Users\\Sajado");
    system("dir");

    return 0;
}

The output window returns the directory listing of the project directory both times. I have also tried using paths other folders, both higher and lower, and cd .. has no effect either.

I am using codeblocks if that helps. I'm no C++ or cmd expert by any means so I may be missing something very obvious. Anyone know why this might be misbehaving?

like image 899
Sajado Avatar asked Nov 20 '25 08:11

Sajado


1 Answers

As explained here, you need to do:

system("cd C:\\Users\\Sajado && dir");

Because

The changed directory only lasts for the duration of the system command. The command starts a separate program, which inherits its current directory from your program, but when that program exits its current directory dies with it.

like image 85
jpo38 Avatar answered Nov 22 '25 22:11

jpo38