c++ - यूनिक्स सिस्टम पर सी++ में सरल ग्लोब?
unix glob (4)
मैं इस पैटर्न के बाद vector<string>
में सभी मिलान पथों को पुनर्प्राप्त करना चाहता हूं:
"/some/path/img*.png"
मैं बस यह कैसे कर सकता हूं?
आप glob()
POSIX लाइब्रेरी फ़ंक्शन का उपयोग कर सकते हैं।
मेरे पास मेरी जिंदगी है। मैंने ग्लोब के चारों ओर एक एसटीएल रैपर बनाया ताकि यह स्ट्रिंग के वेक्टर लौटा सके और ग्लोब परिणाम मुक्त करने का ख्याल रखे। बिल्कुल बहुत कुशल नहीं है लेकिन यह कोड थोड़ा और पठनीय है और कुछ उपयोग करने में आसान कहेंगे।
#include <glob.h> // glob(), globfree()
#include <string.h> // memset()
#include <vector>
#include <stdexcept>
#include <string>
#include <sstream>
std::vector<std::string> glob(const std::string& pattern) {
using namespace std;
// glob struct resides on the stack
glob_t glob_result;
memset(&glob_result, 0, sizeof(glob_result));
// do the glob operation
int return_value = glob(pattern.c_str(), GLOB_TILDE, NULL, &glob_result);
if(return_value != 0) {
globfree(&glob_result);
stringstream ss;
ss << "glob() failed with return_value " << return_value << endl;
throw std::runtime_error(ss.str());
}
// collect all the filenames into a std::list<std::string>
vector<string> filenames;
for(size_t i = 0; i < glob_result.gl_pathc; ++i) {
filenames.push_back(string(glob_result.gl_pathv[i]));
}
// cleanup
globfree(&glob_result);
// done
return filenames;
}
मैंने कुछ समय पहले विंडोज और लिनक्स (शायद अन्य * निक्स पर भी काम करता है) के लिए एक सरल glob लाइब्रेरी लिखी थी, जब मैं ऊब गया था, तो इसे पसंद करने के लिए स्वतंत्र महसूस करें।
उदाहरण का उपयोग:
#include <iostream>
#include "glob.h"
int main(int argc, char **argv) {
glob::Glob glob(argv[1]);
while (glob) {
std::cout << glob.GetFileName() << std::endl;
glob.Next();
}
}
सबसे अधिक संभावना http://www.boost.org/doc/libs/release/libs/regex/ आपको सबसे नज़दीक मिलेगा। एक अच्छा मौका है कि इसे सी ++ 11 में समर्थित किया जाएगा।