Last active
October 9, 2021 21:53
-
-
Save Auax/1d8e7fee524dda86fbe96004c7813ace to your computer and use it in GitHub Desktop.
File finder sample C++ code by Auax.
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 <chrono> | |
| #include <filesystem> | |
| #include <stdlib.h> | |
| // set filesystem namespace | |
| namespace fs = std::filesystem; | |
| std::string getOsName() | |
| { | |
| #ifdef _WIN32 | |
| return "Win-32"; | |
| #elif _WIN64 | |
| return "Win-64"; | |
| #elif __APPLE__ || __MACH__ | |
| return "MacOS"; | |
| #elif __linux__ | |
| return "Linux"; | |
| #elif __FreeBSD__ | |
| return "FreeBSD"; | |
| #elif __unix || __unix__ | |
| return "Unix"; | |
| #else | |
| return "Other"; | |
| #endif | |
| } | |
| bool getEnvVarName(const char** const var) { | |
| std::string OS = getOsName(); | |
| if (OS == "Win-32" || OS == "Win-64") *var = "USERPROFILE"; | |
| else if (OS != "Other") *var = "HOME"; | |
| else | |
| { | |
| return false; | |
| } | |
| return true; | |
| } | |
| int main() | |
| { | |
| std::cout << "Enter the filename: "; | |
| std::string fileName; | |
| std::cin >> fileName; | |
| // get env var | |
| const char* envName; | |
| bool isOtherOS; | |
| isOtherOS = getEnvVarName(&envName); | |
| // Exit in case of undefined envName and undefined OS. | |
| if (!isOtherOS) exit(1); | |
| // _dupenv_s | |
| char* buf = nullptr; | |
| size_t sz = 0; | |
| if (_dupenv_s(&buf, &sz, envName) == 0 && buf != nullptr) | |
| { | |
| // Start measuring time | |
| auto begin = std::chrono::high_resolution_clock::now(); | |
| free(buf); // free buffer | |
| int nOfFiles = 0; | |
| std::string currentPath; | |
| for (const auto& entry : fs::recursive_directory_iterator(buf, std::filesystem::directory_options::skip_permission_denied)) { | |
| try { | |
| std::string path = entry.path().string(); | |
| std::string currentFile = path.substr(path.find_last_of("/\\") + 1); | |
| if (currentFile == fileName) { | |
| currentPath = path; | |
| break; | |
| } | |
| } | |
| catch (...) { | |
| } | |
| nOfFiles++; | |
| } | |
| std::cout << "Number of analyzed files: " << nOfFiles << "\n"; | |
| std::cout << "File path: " << currentPath << "\n"; | |
| auto end = std::chrono::high_resolution_clock::now(); | |
| auto elapsed = std::chrono::duration_cast<std::chrono::nanoseconds>(end - begin); | |
| printf("Time: %.3f seconds.\n", elapsed.count() * 1e-9); | |
| system("pause"); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment