How to get file extension from string in C++

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

    I use these two functions to get the extension and filename without extension:

    std::string fileExtension(std::string file){
    
        std::size_t found = file.find_last_of(".");
        return file.substr(found+1);
    
    }
    
    std::string fileNameWithoutExtension(std::string file){
    
        std::size_t found = file.find_last_of(".");
        return file.substr(0,found);    
    }
    

    And these regex approaches for certain extra requirements:

    std::string fileExtension(std::string file){
    
        std::regex re(".*[^\\.]+\\.([^\\.]+$)");
        std::smatch result;
        if(std::regex_match(file,result,re))return result[1];
        else return "";
    
    }
    
    std::string fileNameWithoutExtension(std::string file){
    
        std::regex re("(.*[^\\.]+)\\.[^\\.]+$");
        std::smatch result;
        if(std::regex_match(file,result,re))return result[1];
        else return file;
    
    }
    

    Extra requirements that are met by the regex method:

    1. If filename is like .config or something like this, extension will be an empty string and filename without extension will be .config.
    2. If filename doesn't have any extension, extention will be an empty string, filename without extension will be the filename unchanged.

    EDIT:

    The extra requirements can also be met by the following:

    std::string fileExtension(const std::string& file){
        std::string::size_type pos=file.find_last_of('.');
        if(pos!=std::string::npos&&pos!=0)return file.substr(pos+1);
        else return "";
    }
    
    
    std::string fileNameWithoutExtension(const std::string& file){
        std::string::size_type pos=file.find_last_of('.');
        if(pos!=std::string::npos&&pos!=0)return file.substr(0,pos);
        else return file;
    }
    

    Note:

    Pass only the filenames (not path) in the above functions.

提交回复
热议问题