【发布时间】:2017-12-30 06:04:54
【问题描述】:
下面,我生成了损坏的代码和相同的固定版本。问题是我无法向自己完全解释为什么前者不起作用但后者起作用。我显然需要复习 C++ 语言的一些非常基本的概念:您能否提供关于我应该复习的内容的指针,并且可能还解释一下为什么我会得到我使用损坏的代码得到的结果。
在代码中提到的'../docs/'目录中,我只是简单地使用linux上的'touch'命令创建了多个不同长度的doc......html文件。
#include <iostream>
#include <regex>
#include <boost/filesystem.hpp>
namespace fs = boost::filesystem;
int main() {
fs::path p("../docs/");
for (auto& dir_it : fs::directory_iterator(p)) {
std::regex re = std::regex("^(doc[a-z]+)\\.html$");
std::smatch matches;
// BROKEN HERE:
if (std::regex_match(dir_it.path().filename().string(), matches, re)) {
std::cout << "\t\t" <<dir_it.path().filename().string();
std::cout << "\t\t\t" << matches[1] << std::endl;
}
}
return 0;
}
生产:
documentati.html ati
documentationt.html �}:ationt
document.html document
documenta.html documenta
docume.html docume
documentat.html documentat
docum.html docum
documentatio.html ��:atio
documen.html documen
docu.html docu
documentation.html ��:ation
documaeuaoeu.html ��:aoeu
注意 1:上面的错误是由超过一定长度的文件名触发的。我只明白那是因为 std::string 对象正在调整自己的大小。
注 2:上面的代码与以下问题中使用的代码非常相似,但使用的是 boost::regex_match 而不是 std::regex_match:
Can I use a mask to iterate files in a directory with Boost?
它以前也适用于我,但现在我使用 GCC 5.4 而不是 GCC 4.6、std::regex 而不是 boost::regex、C++11 和一个更新版本的 boost::filesystem。哪个更改是相关的,导致工作代码被破坏?
固定:
#include <iostream>
#include <regex>
#include <boost/filesystem.hpp>
namespace fs = boost::filesystem;
int main() {
fs::path p("../docs/");
for (auto& dir_it : fs::directory_iterator(p)) {
std::regex re = std::regex("^(doc[a-z]+)\\.html$");
std::smatch matches;
std::string p = dir_it.path().filename().string();
if (std::regex_match(p, matches, re)) {
std::cout << "\t\t" <<dir_it.path().filename().string();
std::cout << "\t\t\t" << matches[1] << std::endl;
}
}
return 0;
}
产生:
documentati.html documentati
documentationt.html documentationt
document.html document
documenta.html documenta
docume.html docume
documentat.html documentat
docum.html docum
documentatio.html documentatio
documen.html documen
docu.html docu
documentation.html documentation
documaeuaoeu.html documaeuaoeu
使用 boost 1.62.0-r1 和 gcc (Gentoo 5.4.0-r3),boost::filesystem 文档似乎没有提供任何关于 path().filename().string() 返回的明确指示:
http://www.boost.org/doc/libs/1_62_0/libs/filesystem/doc/reference.html#path-filename
看来这取决于:
Why does boost::filesystem::path::string() return by value on Windows and by reference on POSIX?
【问题讨论】:
标签: c++ regex string c++11 boost-filesystem