[英]Executing Batch File From C++ with Spaces in the Path
I want to execute a batch file using system()
and the path to the file will be passed to the function so it will look like this: 我想使用
system()
执行批处理文件,该文件的路径将传递给该函数,因此它将如下所示:
void executeBatch(char* BatchFile){
system(BatchFile);
}
Now the issue is that the path passed in will not have the escape quotes to ignore spaces for example the user would input: 现在的问题是,传入的路径将没有转义引号来忽略空格,例如用户将输入:
"C:\\Users\\500543\\Documents\\Batch File Project\\Testing.bat"
How do I add escape quotes to the path passed in? 如何在转义的路径中添加转义引号?
So I essentually change: 所以我本质上改变了:
"C:\\Users\\500543\\Documents\\Batch File Project\\Testing.bat"
to 至
"\"C:\\Users\\500543\\Documents\\Batch File Project\\Testing.bat\""
Try 尝试
system("\"C:\\Users\\500543\\Documents\\Batch File Project\\Testing.bat\"");
As for your additional question from your comment, you have to use: 至于您的评论中的其他问题,您必须使用:
char* it = "\"C:\\Users\\500543\\Documents\\Batch File Project\\Testing.bat\"";
system(it);
then. 然后。
As for your edited question, since you've marked the question to use c++ , here's a c++ solution how to implement your function correctly: 至于您已编辑的问题,由于您已标记了使用c ++的问题,因此以下是一种c ++解决方案,该方法如何正确实现您的函数:
#include <sstream>
int executeBatch(const char* fullBatchFileName)
{
std::ostringstream oss;
oss << '\"' << fullBatchFileName << '\"';
return system(oss.str().c_str());
}
Don't make this an XY problem now! 现在不要将其设为XY问题! I think you should have understood the principle from these samples: Just wrap your batch file name within a pair of double-quote characters (
'\\"'
), that the shell can interpret it correctly. There are also pure c library methods available to achieve this (see <cstring>
) but I wouldn't recommend these, if you can use the c++ standard library. 我认为您应该已经从这些示例中了解了原理:将批处理文件名包装在一对双引号字符(
'\\"'
)中,以使Shell能够正确解释它。还有一些纯c库方法可用于实现这一点(请参见<cstring>
),但是如果可以使用c ++标准库,我将不推荐这些。
尝试在命令行周围添加转义的双引号,即
system("\"C:\\Users\\500543\\Documents\\Batch File Project\\Testing.bat\"");
您需要转义引号:
system("\"C:\\Users\\500543\\Documents\\Batch File Project\\Testing.bat\"");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.