user2179969
user2179969

Reputation: 31

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.

Upvotes: 3

Views: 2580

Answers (3)

Aacini
Aacini

Reputation: 67216

Perhaps there is a misunderstanding here (if so, I apologize), but the standard way to "further interact with cmd prompt" is via command-line commands, and the standard way "to write a program to control the windows cmd prompt" is via a Batch file. For example, the following Batch file open the cmd prompt (when it is executed via a double click in the Explorer), go to a specific directory (C:/Program Files/) and run an exe in that folder:

@echo off
cd "C:/Program Files/"
nameOfTheProgram.exe

Upvotes: 1

typ1232
typ1232

Reputation: 5607

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

Upvotes: 1

user123
user123

Reputation: 9071

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

Upvotes: 2

Related Questions