Reputation:
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
int main(){
char command[20];
system("dir");
while(1){
printf("\n\n");
scanf("%s", &command);
system(command);
}
return 0;
}
this is my code, it's a console app written in C and I wanna be able to control the cmd prompt of my computer, whenever I run new command like cd..
the path always goes back to where it was before, how do i make it like a process? sorry I'm new to it.
Upvotes: 2
Views: 146
Reputation: 1359
I have used a little trick which worked just fine. Let's imagine you want to launch an app located in "C:/Program Files"
.
const char applicationPath[] = "cd C:/Program Files/App&&";
bool sytemCallsToApp(void) {
char cmd[200] = "";
strcpy(cmd, applicationPath); // cmd to access app
strcat(cmd, "app.exe");
strcat(cmd, "&&HERE YOUR NEXT COMMAND"); // This command will be concatenated after the && thus executed just after cd
if (system(cmd) != 0)
return false; // If failed exit
// Use strcpy to modify the content of cmd[]
// Use strcat to add instructions to cmd
// Add && when you want to execute multiple cmd in one system call
// Don't forget system() returns values depending of your calls. It'd be wise to check them.
return true;
}
Upvotes: 0
Reputation: 726479
You need to do it yourself: passing cd
to system(...)
would no longer do the trick, because your own code is running under the control of a command shell, which believes that the current directory is what it was when you started running your program.
It is a job of the command shell, cmd
, to keep track of the current directory. Since you are coding a command shell, you need to keep track of the current location in the directory tree.
You would also need to pass the location to each command that you are running. This task becomes very tricky, though - far beyond a simple pass-through code.
Upvotes: 0
Reputation: 399703
You can't.
The cd
command in typical command-line interpreters is an internal command, i.e. built into the command interpreter itself. This is because the current directory is a property of the process itself, and a child process (which is what system()
creates, in most cases) can't change the current directory of its parent.
Upvotes: 4