简体   繁体   中英

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:

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 , here's a c++ solution how to implement your function correctly:

#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! 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.

尝试在命令行周围添加转义的双引号,即

system("\"C:\\Users\\500543\\Documents\\Batch File Project\\Testing.bat\"");

您需要转义引号:

     system("\"C:\\Users\\500543\\Documents\\Batch File Project\\Testing.bat\"");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM