Winapi Windows上system()和_popen()的替代方案
这与: 我正在尝试做完全相同的事情,只是我的程序需要将“带空格的多个参数”传递给命令。我需要命令行输出和进程的退出代码 示例:使用Textpad的示例。我真正使用的应用程序在stdout上打印东西Winapi Windows上system()和_popen()的替代方案,winapi,Winapi,这与: 我正在尝试做完全相同的事情,只是我的程序需要将“带空格的多个参数”传递给命令。我需要命令行输出和进程的退出代码 示例:使用Textpad的示例。我真正使用的应用程序在stdout上打印东西 string command1=“\”C:\Program Files\TextPad 5\TextPad.exe \“C:\readme0.txt”; string command2=“\”C:\Program Files\TextPad 5\TextPad.exe\”\“C:\read me2.
string command1=“\”C:\Program Files\TextPad 5\TextPad.exe \“C:\readme0.txt”;
string command2=“\”C:\Program Files\TextPad 5\TextPad.exe\”\“C:\read me2.txt\”;
cout我想这就是您要寻找的。以下内容解决了路径中的空格问题。但是,捕获命令的输出要困难得多:
#include <string>
#include <cstdlib>
using namespace std;
int main() {
string cmd = "\"c:\\program files\\notepad++\\notepad++.exe\"";
system( cmd.c_str() );
return 0;
}
#包括
#包括
使用名称空间std;
int main(){
string cmd=“\”c:\\program files\\notepad++\\notepad++.exe\”;
系统(cmd.c_str());
返回0;
}
切勿在Windows中使用system()!
只需重定向i/o句柄。我这样做(注意-这是VB.NET代码),因此我可以将命令的输出写入日志文件(它包装在RunCommand()
方法中):
许多实用程序库已经将这段不可移植的代码打包成一个可移植的接口。例如,请参阅Qt的QProcess。由_popen()和system()使用的最低级别Windows API函数是CreateProcess()
但是CreateProcess()的使用并不是那么简单,尤其是当您想要获取进程的输出或写入进程的输入时
CreateProcess()肯定会处理包含空格字符的文件名(只要它们是以引号的方式编写的)。示例代码中的反斜杠是单字符吗?在C字符串中,您需要使用“\\”使C转义为单个反斜杠,但您可能知道这一点,并且StackOverflow格式代码刚刚将您的示例搞乱了……是的,我的双反斜杠已被替换为单反斜杠。
#include <string>
#include <cstdlib>
using namespace std;
int main() {
string cmd = "\"c:\\program files\\notepad++\\notepad++.exe\"";
system( cmd.c_str() );
return 0;
}
Try
Dim myprocess As New Process()
myprocess.StartInfo.FileName = "C:\Program Files\TextPad 5\Textpad.exe"
myprocess.StartInfo.RedirectStandardOutput = True
myprocess.StartInfo.UseShellExecute = False
' inArgs are the arguments on the command line to the program
myprocess.StartInfo.WindowStyle = ProcessWindowStyle.Hidden
myprocess.StartInfo.Arguments = "C:\readme0.txt"
' the dir to set as default when the program runs
Then myprocess.StartInfo.WorkingDirectory = "C:\Program Files\TextPad 5\"
myprocess.Start()
' grab a reader to the standard output of the program
procReader = myprocess.StandardOutput()
' read all the output from the process
While (Not procReader.EndOfStream)
procLine = procReader.ReadLine()
' write the output to my log
writeNotes(procLine)
End While
procReader.Close()
Catch ex As Exception
' Write the error to my log
writeErrors("Couldn't execute command "C:\Program Files\TextPad 5\Textpad.exe", ex)
End Try