in c++ how to iterate over files in a directory, whose names ends with .json?
- User
in c++ how to iterate over files in a directory, whose names ends with .json?
- Assistant
You can use the
std::filesystemlibrary to iterate over files in a directory in C++. Here is an example code snippet to iterate over files in a directory and check if their names end with.json:#include <iostream> #include <filesystem> #include <string> namespace fs = std::filesystem; int main() { std::string path = "/path/to/directory"; for (const auto& entry : fs::directory_iterator(path)) { if (entry.is_regular_file() && entry.path().extension() == ".json") { std::cout << entry.path() << std::endl; } } return 0; }Replace the
/path/to/directorywith the path to the directory you want to iterate over. This code will iterate over all files in the directory and print the path of the files whose names end with.json. - User
Nice, now I want to know if there is a better way to do this:
for (const auto& entry : fs::directory_iterator(exePath + "/conversations/")) { if (entry.is_regular_file() && entry.path().extension() == ".json") { std::ifstream file(entry.path()); if (file.is_open()) { nlohmann::json conversationJson; file >> conversationJson; file.close();
conversationName = ; conversations.emplace(conversationJson["Name"].get<std::string>(), entry.path()) } } } - Assistant
Your code snippet looks good. One potential improvement could be to use
std::ifstream::opento open the file instead of constructing anstd::ifstreamobject and then checking if it is open. Here is the updated code snippet:#include <iostream> #include <filesystem> #include <fstream> #include <string> #include <nlohmann/json.hpp> using json = nlohmann::json; namespace fs = std::filesystem; int main() { std::string exePath = "./path/to/executable"; std::string conversationName; std::map<std::string, std::string> conversations; for (const auto& entry : fs::directory_iterator(exePath + "/conversations/")) { if (entry.is_regular_file() && entry.path().extension() == ".json") { std::ifstream file; file.open(entry.path()); if (file.is_open()) { json conversationJson; file >> conversationJson; file.close(); conversationName = conversationJson["Name"].get<std::string>(); conversations.emplace(conversationName, entry.path()); } else { std::cerr << "Failed to open file: " << entry.path() << std::endl; } } } // Do something with the conversations map return 0; } - User
Perfect, now how can I add all the keys (conversationNames to a wxListBox named listBoxConversation?
- Assistant
You can add all the conversation names to a
wxListBoxnamedlistBoxConversationby iterating over the conversations map and adding each key to the listbox. Here is updated code snippet to add conversation names to :