3

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?

Sajado
  • 31
  • 1
  • 1
  • 3
  • 3
    The `system()` calls are independent. You will get a new environment each time. To do what you want create a batch file and execute that from cmd.exe in a single `system()`. – drescherjm Nov 20 '16 at 19:52
  • Why not using `chdir`? – jpo38 Nov 20 '16 at 19:52

2 Answers2

6

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.

Community
  • 1
  • 1
jpo38
  • 20,821
  • 10
  • 70
  • 151
0

As commented @drescherjm pointed out, system calls are interpreted in isolation of each other so if you change the working directory in one it will not be reflected in a subsequent call.

You can do this: system("cd C:\\Users\\Sajado && dir"); or, better yet, use an argument to the dir command: system("dir C:\\Users\\Sajado");

Govind Parmar
  • 20,656
  • 7
  • 53
  • 85