Get a file name from a path

前端 未结 21 1594
面向向阳花
面向向阳花 2020-11-30 23:55

What is the simplest way to get the file name that from a path?

string filename = \"C:\\\\MyDirectory\\\\MyFile.bat\"

In this example, I s

21条回答
  •  死守一世寂寞
    2020-12-01 00:22

    The simplest solution is to use something like boost::filesystem. If for some reason this isn't an option...

    Doing this correctly will require some system dependent code: under Windows, either '\\' or '/' can be a path separator; under Unix, only '/' works, and under other systems, who knows. The obvious solution would be something like:

    std::string
    basename( std::string const& pathname )
    {
        return std::string( 
            std::find_if( pathname.rbegin(), pathname.rend(),
                          MatchPathSeparator() ).base(),
            pathname.end() );
    }
    

    , with MatchPathSeparator being defined in a system dependent header as either:

    struct MatchPathSeparator
    {
        bool operator()( char ch ) const
        {
            return ch == '/';
        }
    };
    

    for Unix, or:

    struct MatchPathSeparator
    {
        bool operator()( char ch ) const
        {
            return ch == '\\' || ch == '/';
        }
    };
    

    for Windows (or something still different for some other unknown system).

    EDIT: I missed the fact that he also wanted to suppress the extention. For that, more of the same:

    std::string
    removeExtension( std::string const& filename )
    {
        std::string::const_reverse_iterator
                            pivot
                = std::find( filename.rbegin(), filename.rend(), '.' );
        return pivot == filename.rend()
            ? filename
            : std::string( filename.begin(), pivot.base() - 1 );
    }
    

    The code is a little bit more complex, because in this case, the base of the reverse iterator is on the wrong side of where we want to cut. (Remember that the base of a reverse iterator is one behind the character the iterator points to.) And even this is a little dubious: I don't like the fact that it can return an empty string, for example. (If the only '.' is the first character of the filename, I'd argue that you should return the full filename. This would require a little bit of extra code to catch the special case.) }

提交回复
热议问题