Question

I want to use the Windows CMD tree command in my C++ console application. My code:

system("cd c:/");
system("tree");

The problem is that the command tree will execute on the folder path where the program is running and not on C://. Is there a way to fix this?

Was it helpful?

Solution 2

You can use SetCurrentDirectory from windows.h. This page has a demonstration: http://msdn.microsoft.com/en-us/library/windows/desktop/aa363806%28v=vs.85%29.aspx

OTHER TIPS

Why not :

system("tree c:\");

?

TREE [drive:][path] [/F] [/A]

   /F   Display the names of the files in each folder.
   /A   Use ASCII instead of extended characters.

Your problem is that the system("cd c:/") is executed in a shell, and then the shell exits. [It's also wrong, because you use the wrong kind of slash, it should be "cd c:\\" - the double backslash is needed to make one backslash in the output, assuming we're talking about a Windows system].

There are a couple of different ways to do this:

  1. Use chdir() (or SetCurrentDirectory) function call to change the main processes current working directory, and then call system("..."). This is the simplest solution.

  2. Generate all your commands into a batch file, then pass the batch file to system.

  3. Open a command shell with something like _popen() and pass commands into the pipe that you get from that.
  4. Manually create pipes and connect them to the standard in and standard out of a process that runs the command prompt.

Just for programs in Windows, include "windows.h", then

SetCurrentDirectory("c:/");
system("pwd");

While I'm still curious why would you want to do this, you can try to run all commands in one system() call:

system("cd c: && c: && tree");

Second c: is needed to change drive letter, in case if you're not currently on drive c: (because cd doesn't do it).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top