如何判斷輸入文件的類型在給定範圍內?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;
      }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章