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

前端 未结 27 3228
情书的邮戳
情书的邮戳 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:13

    This works for me. I'm sorry if I cannot remember the source. It is probably from a man page.

    #include 
    
    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/");
    }
    

提交回复
热议问题