2012-04-28 13 views
20

से फ़ाइल नाम निकालने का तरीका मैंC++ पथ स्ट्रिंग

const char *pathname = "..\somepath\somemorepath\somefile.ext"; 

कैसे को बदलने के लिए है कि

"..\somepath\somemorepath" 

में है?

+0

बूस्ट में एक अच्छा 'फाइल सिस्टम :: पथ' वर्ग है ... – Cameron

उत्तर

30

का उपयोग सबसे आसान तरीका है std::string

string s1("../somepath/somemorepath/somefile.ext"); 
string s2("..\\somepath\\somemorepath\\somefile.ext"); 
cout << s1.substr(0, s1.find_last_of("\\/")) << endl; 
cout << s2.substr(0, s2.find_last_of("\\/")) << endl; 

की find_last_of सदस्य समारोह यह समाधान दोनों आगे और पीछे स्लैश के साथ काम करता उपयोग करने के लिए है।

+3

यह मानता है कि उपयोगकर्ता कभी भी अपने फ़ाइल नामों में कानूनी स्लैश कानूनी नहीं रखता है – Potatoswatter

+0

मेरे लिए काम करता है :) धन्यवाद! – Mat

+0

मेरे लिए काम नहीं किया, लेकिन यह http://stackoverflow.com/questions/8518743/get-directory-from-file-path-c – brad

4

अंतिम बैकस्लैश ढूंढने और स्ट्रिंग को पट्टी करने के लिए strrchr() का उपयोग करें।

char *pos = strrchr(pathname, '\\'); 
if (pos != NULL) { 
    *pos = '\0'; //this will put the null terminator here. you can also copy to another string if you want 
} 
+2

क्या होगा यदि यह आगे फॉरवर्ड स्लैश ('/') है? – Cameron

5

Windows 8 पर, PathCchRemoveFileSpec का उपयोग Pathcch.h

PathCchRemoveFileSpec में पाया जा सकता है जो एक पथ का अंतिम तत्व निकाला जाएगा, इसलिए यदि आप इसे एक निर्देशिका पथ गुजरती हैं, पिछले फ़ोल्डर छीन लिया जाएगा।
आप इस से बचने के लिए चाहते हैं, और यदि आप अनिश्चित हैं अगर एक फ़ाइल पथ एक निर्देशिका है, तो का उपयोग PathIsDirectory

PathCchRemoveFileSpec आगे स्लैश युक्त रास्तों पर अपेक्षा के अनुरूप व्यवहार नहीं करता है।

+1

केवल विंडोज 8 पर – Liviu

संबंधित मुद्दे