Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run shell commands in a C program [closed]

Tags:

c

cmd

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

like image 601
Shivam Upadhyay Avatar asked Jul 17 '15 17:07

Shivam Upadhyay


People also ask

Which function is used to execute a shell command from within a process?

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.

How do you end a program in shell?

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 .


1 Answers

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).

like image 139
Jay Bosamiya Avatar answered Sep 29 '22 05:09

Jay Bosamiya