如何从我的C或c++代码中确定目录中的文件列表?

我不允许在程序中执行ls命令并解析结果。


当前回答

这对我很有用。如果我不记得出处,我很抱歉。它可能来自一个手册页。

#include <ftw.h>

int AnalizeDirectoryElement (const char *fpath, 
                            const struct stat *sb,
                            int tflag, 
                            struct FTW *ftwbuf) {

  if (tflag == FTW_F) {
    std::string strFileName(fpath);

    DoSomethingWith(strFileName);
  }
  return 0; 
}

void WalkDirectoryTree (const char * pchFileName) {

  int nFlags = 0;

  if (nftw(pchFileName, AnalizeDirectoryElement, 20, nFlags) == -1) {
    perror("nftw");
  }
}

int main() {
  WalkDirectoryTree("some_dir/");
}

其他回答

尝试x平台方法

http://www.boost.org/doc/libs/1_38_0/libs/filesystem/doc/index.htm

或者只是使用特定于操作系统的文件。

不幸的是,c++标准并没有定义这样处理文件和文件夹的标准方法。

由于没有跨平台的方法,最好的跨平台方法是使用boost文件系统模块之类的库。

跨平台提升方法:

The following function, given a directory path and a file name, recursively searches the directory and its sub-directories for the file name, returning a bool, and if successful, the path to the file that was found. bool find_file(const path & dir_path, // in this directory, const std::string & file_name, // search for this name, path & path_found) // placing path here if found { if (!exists(dir_path)) return false; directory_iterator end_itr; // default construction yields past-the-end for (directory_iterator itr(dir_path); itr != end_itr; ++itr) { if (is_directory(itr->status())) { if (find_file(itr->path(), file_name, path_found)) return true; } else if (itr->leaf() == file_name) // see below { path_found = itr->path(); return true; } } return false; }

来源来自上面提到的boost页面。

对于Unix/Linux系统:

您可以使用opendir / readdir / closedir。

在目录中搜索条目“name”的示例代码如下: Len = strlen(name); Dirp = opendir("."); ((dp = readdir(dirp)) != NULL) 如果(dp - > d_namlen = = len & & !比较字符串(dp - > d_name,名字)){ (空白)closedir (dirp); 返回发现; } (空白)closedir (dirp); 返回NOT_FOUND;

来自上述手册页的源代码。

对于基于windows的系统:

你可以使用Win32 API的FindFirstFile / FindNextFile / FindClose函数。

The following C++ example shows you a minimal use of FindFirstFile. #include <windows.h> #include <tchar.h> #include <stdio.h> void _tmain(int argc, TCHAR *argv[]) { WIN32_FIND_DATA FindFileData; HANDLE hFind; if( argc != 2 ) { _tprintf(TEXT("Usage: %s [target_file]\n"), argv[0]); return; } _tprintf (TEXT("Target file is %s\n"), argv[1]); hFind = FindFirstFile(argv[1], &FindFileData); if (hFind == INVALID_HANDLE_VALUE) { printf ("FindFirstFile failed (%d)\n", GetLastError()); return; } else { _tprintf (TEXT("The first file found is %s\n"), FindFileData.cFileName); FindClose(hFind); } }

来自上述msdn页面的源代码。

彼得·帕克的解决方案,但没有用于:

#include <algorithm>
#include <filesystem>
#include <ranges>
#include <vector>

using namespace std;

int main() {
    vector<filesystem::path> filePaths;
    ranges::transform(filesystem::directory_iterator("."),     
    back_inserter(filePaths), [](const auto& dirFile){return dirFile.path();} );
}

我试图遵循两个回答中给出的示例,可能值得注意的是,似乎std::filesystem::directory_entry已被更改为不重载<<操作符。而不是std::cout << p << std::endl;我必须使用以下能够编译并让它工作:

#include <iostream>
#include <filesystem>
#include <string>
namespace fs = std::filesystem;

int main() {
    std::string path = "/path/to/directory";
    for(const auto& p : fs::directory_iterator(path))
        std::cout << p.path() << std::endl;
}

试图将p单独传递给std::cout <<会导致丢失重载错误。

这个答案应该适用于Windows用户在使用Visual Studio和任何其他答案时遇到的问题。

Download the dirent.h file from the github page. But is better to just use the Raw dirent.h file and follow my steps below (it is how I got it to work). Github page for dirent.h for Windows: Github page for dirent.h Raw Dirent File: Raw dirent.h File Go to your project and Add a new Item (Ctrl+Shift+A). Add a header file (.h) and name it dirent.h. Paste the Raw dirent.h File code into your header. Include "dirent.h" in your code. Put the below void filefinder() method in your code and call it from your main function or edit the function how you want to use it. #include <stdio.h> #include <string.h> #include "dirent.h" string path = "C:/folder"; //Put a valid path here for folder void filefinder() { DIR *directory = opendir(path.c_str()); struct dirent *direntStruct; if (directory != NULL) { while (direntStruct = readdir(directory)) { printf("File Name: %s\n", direntStruct->d_name); //If you are using <stdio.h> //std::cout << direntStruct->d_name << std::endl; //If you are using <iostream> } } closedir(directory); }