【问题标题】:How do I make sure a string contains one element and also doesn't contain another? // How do I check a file's type?如何确保字符串包含一个元素并且不包含另一个? // 如何检查文件的类型?
【发布时间】:2021-06-15 16:18:08
【问题描述】:

我有一个文件路径fileLocation(来自std::filesystem::recursive_directory_iterator)并试图确定它是否属于“.png”类型。 我期待文件目录、png 文件和 mcmeta 文件,它们的名称中包含 .png 行。

换句话说,我需要一个 if 语句将 C:\files\file.png 与 C:\files 和 C:\files\file.png.mcmeta 分开

我试过了

if (fileLocation.path().string().find(".png") == fileLocation.path().string().size()-4) {/*...*/}

但由于某种原因,它只在非 png 文件 之后 的文件中返回了一个错误值。

【问题讨论】:

  • 您可以使用std::string::length() 或std::string::size 来检查字符串是否包含一个元素。
  • 除非您在文件中有某种标识符,否则您实际上无法检查文件的类型。在许多操作系统中,名称不必与文件的类型或用途相关。以臭名昭著的扩展名“.dat”为例。我也可以有一个扩展名为“.txt”的可执行文件。另外,例如“.h”——你不知道它是 C++ 头文件还是 C 语言头文件。
  • @ThomasMatthews 这行得通。我建议您将此作为答案,以便我接受。

标签: c++ string find


【解决方案1】:

对于基于文件命名约定的更复杂的搜索,我使用如下内容:

#include <filesystem>
#include <iostream>
#include <string>
#include <vector>
namespace fs = std::filesystem;
int main(int argc, char** argv) {
  std::string input_dir{"/home/user/Pictures/"};
  std::vector<std::string> pngs;
  for(auto& f : fs::directory_iterator(input_dir)) {
    auto fn = f.path().filename().string();
    auto ext = fn.substr(fn.rfind("."), fn.size()-1);
    if(ext.find(".png") != std::string::npos)
      pngs.push_back(fn);
    else
      std::cout << fn << " is not a png.\n";
  }
  return EXIT_SUCCESS;

【讨论】:

    猜你喜欢
    • 2021-05-06
    • 2017-08-04
    • 1970-01-01
    • 2022-11-14
    • 2011-01-15
    • 1970-01-01
    • 1970-01-01
    • 2010-11-20
    • 2013-03-13
    相关资源
    最近更新 更多