如何处理boost :: fileSystem ::路径的空间

How to deal with spaces for boost::filesystem::path

本文关键字:fileSystem 路径 空间 boost 何处理 处理      更新时间:2023-10-16

我正在尝试从用户输入中获取目录,并将其存储在boost库中的路径对象中。当目录中没有空间,例如C: Windows System32 file.exe但是,当尝试使用C: Program Files file.exe时,它不起作用,该程序只是退出。我正在考虑将输入作为字符串,然后在其上操作以用逃生字符替换空格。有更好的方法吗?

boost::filesystem::path path;
std::cout << "Please enter the path for the file you would like to hash:" << std::endl;
std::cout << "E.g. C:\Program Files\iTunes\iTunes.exe" << std::endl;
std::cin >> path;   

然后将路径传递到一个函数以获得哈希。对于没有空间的路径,可以正常工作,但在空间中,程序就会退出。

std::string md5_file(boost::filesystem::path &file)
{
/* Takes a file and returns the md5 hash. */
// Create new hash wrapper
hashwrapper *myWrapper = new md5wrapper();
std::string hash;
// Hash file
try 
{
    hash = myWrapper->getHashFromFile(file.string());
}
catch (hlException &e) 
{
    std::cerr << "Error(" << e.error_number() << "): " << e.error_message() << std::endl;
}
// Clean up
delete myWrapper;
return hash;
}

您的问题与boost :: filesystem ::路径无关。您的输入有问题。如果路径有空间,则cin >> string_variable将读取到第一个白空间分离器。

尝试检查它:

[boost::filesystem::path][1] path;
std::cout << "Please enter the path for the file you would like to hash:" << std::endl;
std::cout << "E.g. C:\Program Files\iTunes\iTunes.exe" << std::endl;
std::cin >> path;
std::cout << path << endl;

输出应该是线路C:\Program

std :: getline在整个字符串中读取空格:

string str;
getline(cin, s);
path = s;