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

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

    This answer should work for Windows users that have had trouble getting this working with Visual Studio with any of the other answers.

    1. 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

    2. Go to your project and Add a new Item (Ctrl+Shift+A). Add a header file (.h) and name it dirent.h.

    3. Paste the Raw dirent.h File code into your header.

    4. Include "dirent.h" in your code.

    5. 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 
      #include 
      #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 
                  //std::cout << direntStruct->d_name << std::endl; //If you are using 
              }
          }
          closedir(directory);
      }
      

提交回复
热议问题