Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get a list of files in a directory in C++? [duplicate]

How do you get a list of files within a directory so each can be processed?

like image 471
DShook Avatar asked Nov 20 '08 19:11

DShook


People also ask

How do I copy all contents from one directory to another?

Answer: Use the cp Command You can use the cp command to copy files locally from one directory to another. The -a option copy files recursively, while preserving the file attributes such as timestamp. The period symbol ( . ) at end of the source path allows to copy all files and folders, including hidden ones.


1 Answers

Here's what I use:

/* Returns a list of files in a directory (except the ones that begin with a dot) */  void GetFilesInDirectory(std::vector<string> &out, const string &directory) { #ifdef WINDOWS     HANDLE dir;     WIN32_FIND_DATA file_data;      if ((dir = FindFirstFile((directory + "/*").c_str(), &file_data)) == INVALID_HANDLE_VALUE)         return; /* No files found */      do {         const string file_name = file_data.cFileName;         const string full_file_name = directory + "/" + file_name;         const bool is_directory = (file_data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0;          if (file_name[0] == '.')             continue;          if (is_directory)             continue;          out.push_back(full_file_name);     } while (FindNextFile(dir, &file_data));      FindClose(dir); #else     DIR *dir;     class dirent *ent;     class stat st;      dir = opendir(directory);     while ((ent = readdir(dir)) != NULL) {         const string file_name = ent->d_name;         const string full_file_name = directory + "/" + file_name;          if (file_name[0] == '.')             continue;          if (stat(full_file_name.c_str(), &st) == -1)             continue;          const bool is_directory = (st.st_mode & S_IFDIR) != 0;          if (is_directory)             continue;          out.push_back(full_file_name);     }     closedir(dir); #endif } // GetFilesInDirectory 
like image 191
Thomas Bonini Avatar answered Sep 30 '22 03:09

Thomas Bonini