Extracting a Filename from a Full Path - C++ File Stream

C++ examples for File Stream:Directory

Description

Extracting a Filename from a Full Path

Demo Code

#include <iostream>
#include <string>

using std::string;

string getFileName(const string& s) {

   char sep = '/';

#ifdef _WIN32/*w w w . j  a  v a2s .  c  om*/
   sep = '\\';
#endif

   size_t i = s.rfind(sep, s.length());
   if (i != string::npos) {
      return(s.substr(i+1, s.length() - i));
   }
   return("");
}

int main(int argc, char** argv) {

   string path = "c:/abc/def";

   std::cout << "The file name is \"" << getFileName(path) << "\"\n";
}

Result


Related Tutorials