C++ extract file name from path

#include <iostream>
#include <string>

std::wstring extract_filename(const std::wstring& filepath)
{
    auto pos = filepath.rfind(L"\\");
    if(pos == std::wstring::npos)
        pos = -1;
    return std::wstring(filepath.begin() + pos + 1, filepath.end());
}

int main()
{
    {
        auto path = L"C:\\Users\\OT\\Downloads\\AppleFileSystemDriver-17.txt";
        std::wcout << extract_filename(path) << std::endl;
    }
    {
        auto path = L"C:\\Users\\OT\\Downloads\\";
        std::wcout << extract_filename(path) << std::endl;
    }
    {
        auto path = L"AppleFileSystemDriver-17.txt";
        std::wcout << extract_filename(path) << std::endl;
    }
    {
        auto path = L"";
        std::wcout << extract_filename(path) << std::endl;
    }
   
   return 0;
}

comments powered by Disqus