Last active
October 11, 2023 17:17
-
-
Save wheresjames/10b650967d070fa795ba3adfb1e0335a to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <string> | |
#include <vector> | |
#include <filesystem> | |
#include <cstdlib> | |
#include <regex> | |
/** This program executes a command for each file in a directory that matches a filter. | |
Usage : test_args <directory> <file-filter> <executable> [extra arguments...] | |
Example : test_args ./path/to/files .*\.glb$ test_conversion --verbose | |
Test : test_args ./path/to/files .*\.glb$ - | |
*/ | |
int main(int argc, char** argv) | |
{ | |
// Check for the minimum number of required arguments. | |
if (argc < 4) | |
{ | |
std::cerr << "Usage: " << argv[0] << " <directory> <file-filter> <executable> [extra arguments...]" << std::endl; | |
return 1; | |
} | |
std::filesystem::path directory(argv[1]); | |
std::string filter = argv[2]; | |
std::string executable = argv[3]; | |
// Store extra arguments if any. | |
std::vector<std::string> extraArgs; | |
for (int i = 4; i < argc; ++i) | |
extraArgs.push_back(argv[i]); | |
std::regex pattern(filter); | |
std::cout << "----------------------------------------" << std::endl; | |
std::cout << "Directory : " << directory << std::endl; | |
std::cout << "Filter : " << filter << std::endl; | |
std::cout << "Executable : " << executable << std::endl; | |
std::cout << "----------------------------------------" << std::endl; | |
try | |
{ | |
// Loop through the files in the directory. | |
for (const auto& entry : std::filesystem::recursive_directory_iterator(directory)) | |
if (entry.is_regular_file() && std::regex_match(entry.path().filename().string(), pattern)) | |
{ | |
std::string command = executable + " " + entry.path().string(); | |
// Append extra arguments to the command if any. | |
for (const auto& arg : extraArgs) | |
command += " " + arg; | |
std::cout << "----------------------------------------" << std::endl; | |
std::cout << "Executing command: " << command << std::endl; | |
if (executable != "-") | |
{ | |
int returnValue = std::system(command.c_str()); | |
if (returnValue != 0) | |
{ std::cerr << "Error: command returned " << returnValue << std::endl; | |
return returnValue; | |
} | |
} | |
} | |
} | |
catch (const std::filesystem::filesystem_error& e) | |
{ | |
std::cerr << "Error: " << e.what() << std::endl; | |
return 1; | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment