C++ Question

Adding filenames from a directory to a char* array. c++

I ame trying to get filenames from a directory and put it in a char* array for latter use. But this dont seem to work the way i want to. When printing it only showes the last filename on all spots.

So my question howe can i add the file names in every spot inside the char*[]?

/*Placed outside*/
int i = 0;
char* Files[20] = {};
/*Placed outside*/

while (handle != INVALID_HANDLE_VALUE)
char buffer[4100];
sprintf_s(buffer, "%ls", search_data.cFileName);
Files[i] = buffer;
if (FindNextFile(handle, &search_data) == FALSE)

/*Printing I use ImGui*/
#define IM_ARRAYSIZE(_ARR) ((int)(sizeof(_ARR)/sizeof(*_ARR)))
static int listbox_item_current = 1;
ImGui::ListBox("", &listbox_item_current, Files, i, 4);

Answer Source

You could use C++ standard filesystem, but for that I guess you would need C++17 (or atleast VS15), not really sure.

You would have to include:

#include <experimental/filesystem>
#include <filesystem>
using namespace std::experimental::filesystem::v1;

Using it should be simple:

int i = 0;
const char * directoryToSearch = "C:\etc\etc";
for (const auto & file : directory_iterator(directoryToSearch)) {
    files[i] = new char[file.path().stem().string().length() + 1];
    strcpy(files[i], file.path().stem().string().c_str());

Indeed, you should clean up the array after you're done using it. Don't forget, not many compilers support this at the moment.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download