天天看點

如何擷取一個檔案字尾?

場景: 圖檔格式判斷和字元大小轉換

用到函數 

strrchr() 從字元的最後一個位置開始讀起 

strchr() 從字元的第一個位置開始讀起 

#include <stdio.h>
#include <iostream>
#include <string>
#include <string.h>
#include <algorithm>

using namespace std;

std::string GetFilePosfix(const char* path)
{//擷取檔案字尾
  std::string path_pos=strrchr(path,'.');
  std::string path_format(path_pos,1);
  std::cout<<"fun:"<<path_format<<endl;
  transform(path_format.begin(),path_format.end(),path_format.begin(),::tolower);
  return path_format;
}

bool IsSupported(const std::string currnet_format,const std::string supported_format)
{//判斷字尾是否是支援的格式
  std::string tmp_str(";");
  tmp_str.append(currnet_format).append(";");

  if(supported_format.find(tmp_str)!= supported_format.npos)//npos 不存在的位置,一般為 -1
  {
    return true;
  }
  return false;
}

int main(int argc,char *argv[])
{
  const char* path="C:/file/test.dd.pnG";
  
  cout<<GetFilePosfix(path)<<endl;
  
  const std::string image_format=";png;bmp;gif;png";

  cout<<IsSupported(GetFilePosfix(path),image_format)<<endl;

  system("pause");
}