Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Control cmd prompt using C

I'm trying to write a C program to control the windows cmd prompt. For example, opening the cmd prompt, go to a specific directory (ex: C:/Program Files/...), and then run an exe in that folder.

Can this be done with C programming? If so, how? So far, I am only aware of system("cmd.exe") to open up the cmd prompt. How would I further interact with cmd prompt?

Thanks.

like image 434
user2179969 Avatar asked Dec 04 '25 15:12

user2179969


2 Answers

This wouldn't be very portable. system calls are often frowned upon, but just to answer your question, the system function does work with the commands you're aiming to use.

For example:

system("notepad.exe my_file.txt");
system("del my_file.txt");
system("pause");

This will open up a file called my_file.txt in notepad, delete it and pause the program.

Again, this is not portable. It's specific to Windows Operating systems. In fact, I don't even think it's guaranteed to work on all releases of Windows. (Don't quote me on that.)

like image 198
user123 Avatar answered Dec 07 '25 05:12

user123


On topic: You could start cmd via "CreateProcess" and send key input via window messages ("SendMessage").

I think you should rethink how you want things to be done. The command prompt is not a kind of API base to do things on windows. It's a tool to do things and get information without writing your own program. If you wirte an own program, you should directly use the WinAPI.

To get started you can google "winapi [whatever you want to do]". In your example "winapi start executable" and you will find functions like "CreateProcess" and "ShellExecute".

like image 30
typ1232 Avatar answered Dec 07 '25 04:12

typ1232