How to get file extension from string in C++

前端 未结 25 2329
迷失自我
迷失自我 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:30

    I'd go with boost::filesystem::extension (std::filesystem::path::extension with C++17) but if you cannot use Boost and you just have to verify the extension, a simple solution is:

    bool ends_with(const std::string &filename, const std::string &ext)
    {
      return ext.length() <= filename.length() &&
             std::equal(ext.rbegin(), ext.rend(), filename.rbegin());
    }
    
    if (ends_with(filename, ".conf"))
    { /* ... */ }
    
    0 讨论(0)
  • 2020-11-30 23:31

    actually the STL can do this without much code, I advise you learn a bit about the STL because it lets you do some fancy things, anyways this is what I use.

    std::string GetFileExtension(const std::string& FileName)
    {
        if(FileName.find_last_of(".") != std::string::npos)
            return FileName.substr(FileName.find_last_of(".")+1);
        return "";
    }
    

    this solution will always return the extension even on strings like "this.a.b.c.d.e.s.mp3" if it cannot find the extension it will return "".

    0 讨论(0)
  • 2020-11-30 23:32

    I used PathFindExtension() function to know whether it is a valid tif file or not.

    #include <Shlwapi.h>
    bool A2iAWrapperUtility::isValidImageFile(string imageFile)
    {
        char * pStrExtension = ::PathFindExtension(imageFile.c_str());
    
        if (pStrExtension != NULL && strcmp(pStrExtension, ".tif") == 0)
        {
            return true;
        }
    
        return false;
    }
    
    0 讨论(0)
  • 2020-11-30 23:33

    If you consider the extension as the last dot and the possible characters after it, but only if they don't contain the directory separator character, the following function returns the extension starting index, or -1 if no extension found. When you have that you can do what ever you want, like strip the extension, change it, check it etc.

    long get_extension_index(string path, char dir_separator = '/') {
        // Look from the end for the first '.',
        // but give up if finding a dir separator char first
        for(long i = path.length() - 1; i >= 0; --i) {
            if(path[i] == '.') {
                return i;
            }
            if(path[i] == dir_separator) {
                return -1;
            }
        }
        return -1;
    }
    
    0 讨论(0)
  • 2020-11-30 23:34

    A NET/CLI version using System::String

       System::String^ GetFileExtension(System::String^ FileName)
       {
           int Ext=FileName->LastIndexOf('.');
           if( Ext != -1 )
               return FileName->Substring(Ext+1);
           return "";
       }
    
    0 讨论(0)
  • 2020-11-30 23:35

    If you use Qt library, you can give a try to QFileInfo's suffix()

    0 讨论(0)
提交回复
热议问题