How do you get a list of files within a directory so each can be processed?
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With