在Windows上的 C++ 中,您只需转义 \ 和 " 在需要的地方,引用参数并 ShellExecute 它。然后,引号内的所有内容都应视为文本。
这应该说明:
#include <iostream>
#include <string>
#include <windows.h>
#include <cstdlib>
using namespace std;
// Escape and quote string for use as Windows command line argument
string qEscape(const string& s) {
string result("\"");
for (string::const_iterator i = s.begin(); i != s.end(); ++i) {
const char c = *i;
const string::const_iterator next = i + 1;
if (c == '"' || (c == '\\' && (next == s.end() || *next == '"'))) {
result += '\\';
}
result += c;
}
result += '"';
return result;
}
int main() {
// Argument value to pass: c:\program files\test\test.exe
const string safe_program = qEscape("c:\\program files\\test\\test.exe");
cout << safe_program << " ";
// Argument value to pass: You're the "best" around.
const string safe_arg0 = qEscape("You're the \"best\" around.");
// Argument value to pass: "Nothing's" gonna ever keep you down.
const string safe_arg1 = qEscape("\"Nothing's\" gonna ever keep you down.");
const string safe_args = safe_arg0 + " " + safe_arg1;
cout << safe_args << "\n\n";
// c:\program files\test\ to pass.
const string bs_at_end_example = qEscape("c:\\program files\\test\\");
cout << bs_at_end_example << "\n\n";
const int result = reinterpret_cast<int>(ShellExecute(NULL, "open", safe_program.c_str(), safe_args.c_str(), NULL, SW_SHOWNORMAL));
if (result < 33) {
cout << "ShellExecute failed with Error code " << result << "\n";
return EXIT_FAILURE;
}
}
但是,对于您使用的任何方法,您都应该对其进行测试,看看它确实可以防止注入。