I am really new to advanced programming (at least this is advanced for me)
I want to learn how to run shell commands through C program on windows
I did search for it and I know it has got something to do with system()
and exec()
but I didn't get a definite answer.
To begin with,i would like to execute cd command and also md command
So if someone can break this down to really basic level,it will be much appreciated. Thank you
P.S. I succeeded in doing so and I know now one shouldn't run system commands through C but this was just an assignment.Thank you
The exec Function The exec() function creates a new shell and executes a given command. The output from the execution is buffered, which means kept in memory, and is available for use in a callback. Let's use exec() function to list all folders and files in our current directory.
You can use Ctrl - C to end a program's execution in the terminal. Using kill without any switches is the same as using -TERM .
Here's a short program that runs dir
from inside a C program.
#include <stdlib.h>
int main() {
system("dir");
return 0;
}
Basically, whatever command you pass as a string inside the parameter for system()
is run using the shell on your system. In your case, since you are working on Windows, it is equivalent to running the string inside your command prompt. This is equivalent to the "DOS Commands" you talk about. However, these are actually shell commands.
Note: In general, you do NOT want to be running system()
since there are almost always a better way of doing things. Also, if your code is just basically what is above, then you're better off writing a batch file (i.e. a .bat
file).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With