How to get file extension from string in C++

前端 未结 25 2419
迷失自我
迷失自我 2020-11-30 22:35

Given a string \"filename.conf\", how to I verify the extension part?

I need a cross platform solution.

25条回答
  •  [愿得一人]
    2020-11-30 23:14

    This is a solution I came up with. Then, I noticed that it is similar to what @serengeor posted.

    It works with std::string and find_last_of, but the basic idea will also work if modified to use char arrays and strrchr. It handles hidden files, and extra dots representing the current directory. It is platform independent.

    string PathGetExtension( string const & path )
    {
      string ext;
    
      // Find the last dot, if any.
      size_t dotIdx = path.find_last_of( "." );
      if ( dotIdx != string::npos )
      {
        // Find the last directory separator, if any.
        size_t dirSepIdx = path.find_last_of( "/\\" );
    
        // If the dot is at the beginning of the file name, do not treat it as a file extension.
        // e.g., a hidden file:  ".alpha".
        // This test also incidentally avoids a dot that is really a current directory indicator.
        // e.g.:  "alpha/./bravo"
        if ( dotIdx > dirSepIdx + 1 )
        {
          ext = path.substr( dotIdx );
        }
      }
    
      return ext;
    }
    

    Unit test:

    int TestPathGetExtension( void )
    {
      int errCount = 0;
    
      string tests[][2] = 
      {
        { "/alpha/bravo.txt", ".txt" },
        { "/alpha/.bravo", "" },
        { ".alpha", "" },
        { "./alpha.txt", ".txt" },
        { "alpha/./bravo", "" },
        { "alpha/./bravo.txt", ".txt" },
        { "./alpha", "" },
        { "c:\\alpha\\bravo.net\\charlie.txt", ".txt" },
      };
    
      int n = sizeof( tests ) / sizeof( tests[0] );
    
      for ( int i = 0; i < n; ++i )
      {
        string ext = PathGetExtension( tests[i][0] );
        if ( ext != tests[i][1] )
        {
          ++errCount;
        }
      }
    
      return errCount;
    }
    

提交回复
热议问题