I have a full path like /a/b/c/text.txt
How to get /a/b/c and text.txt using c++? Prefer to use some standard library function.
I plan to use
substring, and find_last_of
I have a full path like /a/b/c/text.txt
How to get /a/b/c and text.txt using c++? Prefer to use some standard library function.
I plan to use
substring, and find_last_of
Use find_last_of
- http://www.cplusplus.com/reference/string/string/find_last_of/
Along with substr should conjecture up a solution for you
You can try the following:
std::string path = "/a/b/c/text.txt";
size_t lastSlash = path.rfind("/");
if (lastSlash != std::string::npos){
std::string filename = path.substr(lastSlash + 1);
std::string folder = path.substr(0, lastSlash);
}
Note that this works only for forward slashes as it is.
Based on the duplication(stackoverflow.com/a/3071694/2082964), I think the following solve the question,
Please note , depends on you need the trailing / or not; for my question, I need, so I modified a little bit.
// string::find_last_of
#include <iostream>
#include <string>
using namespace std;
void SplitFilename (const string& str)
{
size_t found;
cout << "Splitting: " << str << endl;
found=str.find_last_of("/\\");
cout << " folder: " << str.substr(0,found+1) << endl;
cout << " file: " << str.substr(found+1) << endl;
}
int main ()
{
string str1 ("/usr/bin/man");
string str2 ("c:\\windows\\winhelp.exe");
SplitFilename (str1);
SplitFilename (str2);
return 0;
}