下面,我產生了破碎的代碼和相同的固定版本。問題是我不能完全向自己解釋爲什麼前者不起作用,但後者卻起作用。我顯然需要回顧一下C++語言的一些非常基本的概念:能否提供我應該查看的內容的指針,並且可能還會解釋爲什麼我會用破碎的代碼得到結果。基本概念與std ::字符串引用,std :: regex和boost :: filesystem
在代碼中引用的'../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
使用升壓1.62.0-R1和gcc(Gentoo的5.4.0-R3),升壓::文件系統文件不會出現()。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?
哦!現在我明白了,看起來很明顯。 +1。謝謝你的時間。 – augustin