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:

  1. Include the necessary headers:
#include <iostream>
#include <cstdlib>
#include <cstdio>
  1. 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;
}
  1. 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;
  1. Use the executeCommand function to run the find 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.

  1. 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);
    }
  1. Print the file paths from the array:
    for (int j = 0; j < i; j++) {
        std::cout << files[j] << std::endl;
    }
  1. 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.