!!!已解决!!!
谢谢大家的帮助,现在所有东西都可以正常工作了。我按照@RSahu的建议修改了我的代码并使其正常工作。
感谢大家的支持,我一直被这个问题困扰着。
对于@Basile:我一定会去看看的,但是对于这段特定的代码,我不会使用它,因为它看起来太复杂了 :) 不过还是感谢你的建议。
原始问题
我正在尝试制作一个C++代码来列出给定目录及其子目录中的所有文件。
快速说明
Idea 是函数list_dirs(_dir, _files, _current_dir)
将从顶级目录开始,并将文件放入向量_files
中,当它找到一个目录时,它将在此目录上调用自身。_current_dir
用于在子目录中添加到文件名之前,因为我需要知道路径结构(它应该生成sitemap.xml)。
在list_dirs
中,有一个对list_dir
的调用,它只返回当前目录中的所有文件,没有区分文件和目录。
我的问题
现在代码所做的是列出原始目录中的所有文件,然后列出一个子目录中的所有文件,但跳过所有其他子目录。它会列出它们,但不会列出其中的文件。
更加神秘的是,它只列出这一个特定目录中的文件,而没有其他文件。我尝试在多个位置运行它,但它从未进入任何其他目录。
先感谢大家,并请注意我是C++的初学者,所以不要太苛刻了;)
LIST_DIR
int list_dir(const std::string& dir, std::vector<std::string>& files){
DIR *dp;
struct dirent *dirp;
unsigned fileCount = 0;
if ((dp = opendir(dir.c_str())) == NULL){
std::cout << "Error opening dir." << std::endl;
}
while ((dirp = readdir(dp)) != NULL){
files.push_back(std::string (dirp->d_name));
fileCount++;
}
closedir(dp);
return fileCount;
}
以及 LIST_DIRS
int list_dirs (const std::string& _dir, std::vector<std::string>& _files, std::string _current_dir){
std::vector<std::string> __files_or_dirs;
list_dir(_dir, __files_or_dirs);
std::vector<std::string>::iterator it = __files_or_dirs.begin();
struct stat sb;
while (it != __files_or_dirs.end()){
if (lstat((&*it)->c_str(), &sb) == 0 && S_ISDIR(sb.st_mode)){
/* how to do this better? */
if (*it == "." || *it == ".."){
__files_or_dirs.erase(it);
continue;
}
/* here it should go into sub-directory */
list_dirs(_dir + *it, _files, _current_dir + *it);
__files_or_dirs.erase(it);
} else {
if (_current_dir.empty()){
_files.push_back(*it);
} else {
_files.push_back(_current_dir + "/" + *it);
}
++it;
}
}
}
list_dirs("somedir", files, "");
所以_current_dir
不等于dir
。我会划掉我的编辑(抱歉,我在一个很晚的时间,没有完全考虑清楚)。 - pstrjds