如何判断输入文件的类型在给定范围内?how to judge whether given file's extension is within list?

  • 背景:
    • 工程中有时需要读入一个文件夹中的所有文件,对其进行一定操作;
    • 但是希望在执行操作之前,对文件类型进行筛选判别,提前去除掉不符合类型要求的文件;
    • 同时又希望文件类型有一定的扩展性,当对类型名进行增删时,只需要对类型名的定义处进行更改,而不希望源代码受到影响;
    • 本文中以图片的常用类型做示范,进行说明;
  • 定义图片常见类型:
    • 采用枚举enum方法定义Img_format
    • 注意添加Img_format_COUNT来对枚举元素个数进行统计,下面将会用到;

      namespace ImageIO
      {
      enum Img_format{jpg, bmp, tiff,tif, png, gif, jpeg, Img_format_COUNT};
      }
  • 定义类型扩展名extension的字符串
    • 定义类型扩展名extension的字符串,与Img_format的类型名进行一一对应;
    • 类型扩展名在使用boost::filesystem读取后是小写;
    • 因为定义static全局变量,为了使用安全,将其限定在ImageIO这个命名空间内;

      namespace ImageIO
      {
      static const char *Img_format_str[] =
      {".jpg", ".bmp", ".tiff", ".tif", ".png", ".gif", ".jpeg"};
      }
  • 获得类型扩展名<vector>向量

    • 使用 方法set_img_format,将扩展名字符串保存在<vector>向量中;
    • 注意:为了获得类型名的个数,使用enum枚举最后一个元素来获得int max = (int)Img_format_COUNT;

      namespace ImageIO
      {
      std::vector<std::string> set_img_format()
      {
      std::vector<std::string> out;
      int max = (int)Img_format_COUNT;
      for (int i = 0; i <max; i++)
      {
      out.push_back(Img_format_str[i]);
      }
      return out;
      }
      }
  • 对类型名判断:

    • 使用 boost::filesystem path.extension().compare()==0 来进行判断;

      namespace ImageIO
      {
      bool is_img_format(const std::string &input_path)
      {
      std::vector<std::string> img_format = set_img_format();
      std::vector<std::string>::iterator it = img_format.begin();
      std::vector<std::string>::iterator it_end = img_format.end();
      fs::path p(input_path);
      for (; it != it_end; it++)
      {
      if (p.extension().compare(*it) == 0)
      {
      return true;
      }
      }
      return false;
      }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章