开发者

dirname(php) similar function in c++

is there is any function in c++ ,similar to dirname in php...it is used to normalize the url

eg
<?php
$url = "../tets/index.html";
$currentURL = "http://example.com/somedir/anotherdir";
echo dirname($c开发者_Python百科urrentURL).substr($url, 2);
?>


No, but implementing it yourself is trivial.

std::string DirName(std::string source)
{
    source.erase(std::find(source.rbegin(), source.rend(), '/').base(), source.end());
    return source;
}

Even better would be to implement it as a method template:

template<typename string_t>
string_t DirName(string_t source)
{
    source.erase(std::find(source.rbegin(), source.rend(), '/').base(), source.end());
    return source;
}

EDIT: And for some reason if you want what @larsmans is talking about in the comment below:

template<typename string_t>
string_t DirName(string_t source)
{
    if (source.size() <= 1) //Make sure it's possible to check the last character.
    {
        return source;
    }
    if (*(source.rbegin() + 1) == '/') //Remove trailing slash if it exists.
    {
        source.pop_back();
    }
    source.erase(std::find(source.rbegin(), source.rend(), '/').base(), source.end());
    return source;
}


Standard C++ has no notion of directories, so you will either have to use a platform-specific function, or a portable library such as Boost.Filesystem.

I wouldn't use such a function on a URL though; try to find a proper URL parsing library.


There is no directory access in the C++ language. You need to implement this with platform dependent functions like FindFirst/FindNext (Microsoft Windows) or with a library like boost (Boost.Filesystem).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜