How can I get the list of files in a directory using C or C++?

前端 未结 27 3176
情书的邮戳
情书的邮戳 2020-11-21 05:30

How can I determine the list of files in a directory from inside my C or C++ code?

I\'m not allowed to execute the ls command and parse the results from

27条回答
  •  别那么骄傲
    2020-11-21 06:10

    Since files and sub directories of a directory are generally stored in a tree structure, an intuitive way is to use DFS algorithm to recursively traverse each of them. Here is an example in windows operating system by using basic file functions in io.h. You can replace these functions in other platform. What I want to express is that the basic idea of DFS perfectly meets this problem.

    #include
    #include
    #include
    using namespace std;
    
    void TraverseFilesUsingDFS(const string& folder_path){
       _finddata_t file_info;
       string any_file_pattern = folder_path + "\\*";
       intptr_t handle = _findfirst(any_file_pattern.c_str(),&file_info);
       //If folder_path exsist, using any_file_pattern will find at least two files "." and "..", 
       //of which "." means current dir and ".." means parent dir
       if (handle == -1){
           cerr << "folder path not exist: " << folder_path << endl;
           exit(-1);
       }
       //iteratively check each file or sub_directory in current folder
       do{
           string file_name=file_info.name; //from char array to string
           //check whtether it is a sub direcotry or a file
           if (file_info.attrib & _A_SUBDIR){
                if (file_name != "." && file_name != ".."){
                   string sub_folder_path = folder_path + "\\" + file_name;                
                   TraverseFilesUsingDFS(sub_folder_path);
                   cout << "a sub_folder path: " << sub_folder_path << endl;
                }
           }
           else
                cout << "file name: " << file_name << endl;
        } while (_findnext(handle, &file_info) == 0);
        //
        _findclose(handle);
    }
    

提交回复
热议问题