bash find into array
To find files using the find
command in a bash script and store the results in an array in C++, you can use the following steps:
- Include the necessary headers:
#include <iostream>
#include <cstdlib>
#include <cstdio>
- Declare a function to execute the bash command and return the output as a string:
std::string executeCommand(const char* command) {
char buffer[128];
std::string result = "";
FILE* pipe = popen(command, "r");
if (pipe) {
while (!feof(pipe)) {
if (fgets(buffer, 128, pipe) != nullptr)
result += buffer;
}
pclose(pipe);
}
return result;
}
- Declare the main function and create an array to store the file paths:
int main() {
std::string files[100]; // Adjust the array size as needed
int i = 0;
- Use the
executeCommand
function to run thefind
command and store the output in a string:
std::string output = executeCommand("find /path/to/search -type f");
Replace /path/to/search
with the actual path where you want to search for files.
- Parse the output string and store each line (file path) in the array:
size_t pos = 0;
while ((pos = output.find("\n")) != std::string::npos) {
files[i++] = output.substr(0, pos);
output.erase(0, pos + 1);
}
- Print the file paths from the array:
for (int j = 0; j < i; j++) {
std::cout << files[j] << std::endl;
}
- End the main function and the program:
return 0;
}
Make sure to replace /path/to/search
with the actual path you want to search for files. Also, adjust the array size (100
in this example) according to your needs.