【发布时间】:2017-04-21 19:42:31
【问题描述】:
我正在尝试从用户输入中获取一个目录并将其存储在来自 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;
}
【问题讨论】:
-
更具体地说明究竟是什么坏了。
filesystem::path处理空格没有问题。 -
您的最小可编译示例在哪里,什么是“一切都中断了?”这是否包括显示器着火或整个街区断电?
-
尝试使用
getline获取用户提供的整行 -
我将支持
getline的建议。最重要的是,为什么myWrapper被定义为指针?似乎您可以通过简单地创建一个本地堆栈变量来从该代码中获得等效的行为。将其委托给动态内存,使用裸指针,这似乎是在维护此代码时导致错误的一种简单方法。
标签: c++ boost path filesystems