Reputation: 3
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?
Upvotes: 0
Views: 2142
Reputation: 13003
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).
Upvotes: 0
Reputation: 53
Just for programs in Windows, include "windows.h", then
SetCurrentDirectory("c:/");
system("pwd");
Upvotes: 0
Reputation: 35408
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.
Upvotes: 1
Reputation: 129374
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:
Use chdir()
(or SetCurrentDirectory
) function call to change the main processes current working directory, and then call system("...")
. This is the simplest solution.
Generate all your commands into a batch file, then pass the batch file to system
.
_popen()
and pass commands into the pipe that you get from that. Upvotes: 0
Reputation: 9904
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
Upvotes: 0