如何从c程序运行命令提示符命令? [英] How to run command prompt commands from a c program?

查看:85
本文介绍了如何从c程序运行命令提示符命令?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在c程序中运行命令提示符命令。该命令应该从文本文件中获取输入,或者它应该从for循环中获取这些输入...我是c编程的新手...

例如:

To运行命令颜色

此命令颜色应该从文本文件中获取输入...文本文件包含像abcd一样的输入,每行输入一次......

I want to run a command prompt command from within a c program. That command should take inputs from a text file or it should take those inputs from a for loop...I am m new to c programming..
eg:
To run a command color
This command color should take inputs from a text file ...text file contains inputs like a b c d each in a single line...

推荐答案

不幸的是你没有提到你正在运行的操作系统。

无论如何我都会尝试使用Windows:



你正在寻找的函数是CreateProcess()

Unfortunately you did not mention which OS you are running on.
I'll try with Windows anyway:

The function you are looking for is CreateProcess()
BOOL WINAPI CreateProcess(
 TEXT("<path and filename of your application>"),
 TEXT("<CommandLine parameters>"),
...
);





您将名称,路径和命令行传递给您的程序运行。

重定向缺点通过在dwFlags中设置标志STARTF_USESTDHANDLES并填充STARTUPINFO结构中的相应成员(下面加下划线)来完成输入和输出。



You pass the name, path and command lines to your program to run.
The redirection of the console input and output is done by setting the flag STARTF_USESTDHANDLES in dwFlags and filling the appropriate members in the STARTUPINFO structure (underlined below).

typedef struct _STARTUPINFO {
  DWORD  cb;
  LPTSTR lpReserved;
  LPTSTR lpDesktop;
  LPTSTR lpTitle;
  DWORD  dwX;
  DWORD  dwY;
  DWORD  dwXSize;
  DWORD  dwYSize;
  DWORD  dwXCountChars;
  DWORD  dwYCountChars;
  DWORD  dwFillAttribute;
  DWORD  dwFlags;
  WORD   wShowWindow;
  WORD   cbReserved2;
  LPBYTE lpReserved2;
  HANDLE hStdInput;
  HANDLE hStdOutput;
  HANDLE hStdError;
} STARTUPINFO, *LPSTARTUPINFO;





这里有MSDN文档的链接以获取更多详细信息:

CreateProcess():

http://msdn.microsoft .com / zh-CN / library / windows / desktop / ms682425(v = vs.85).aspx [ ^ ]



STARTUPINFO结构:

http:/ /msdn.microsoft.com/en-us/library/windows/desktop/ms686331(v=vs.85).aspx [ ^ ]



如果这不是预期的操作系统,请告诉我们w。



祝你的项目好运!

Steve



Here the links to the MSDN documentation for more details:
CreateProcess():
http://msdn.microsoft.com/en-us/library/windows/desktop/ms682425(v=vs.85).aspx[^]

The STARTUPINFO structure:
http://msdn.microsoft.com/en-us/library/windows/desktop/ms686331(v=vs.85).aspx[^]

If this is not the intended OS, please let us know.

Good luck with your project!
Steve


你可能想要 ShellExecute cmd.exe。

这里是文档 [ ^ ]
You may want to ShellExecute "cmd.exe".
Here the doc[^]


这将适用于Posix系统(包括Windows)。



示例:



This will work on Posix systems (including Windows).

Example:

#include <stdlib.h>

system("cmd.exe");
system("bash");
</stdlib.h>





http://pubs.opengroup.org/onlinepubs/009695399/functions/system.html [ ^ ]


这篇关于如何从c程序运行命令提示符命令?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆