检查文件夹名称是否以特定字符串开头

Check if folders name starts with certain string

你好所以基本上我想要的是遍历给定目录中的所有文件夹并找到一个名称中包含 4p 的文件夹

for (const auto& folderIter : filesystem::directory_iterator(roaming))
{
    if (folderIter.path() == folderIter.path().string().contains("4p") != std::string::npos)
    {
        filesystem::remove(folderIter.path());
    }
}

但是这段代码不起作用

自从您告诉:

im trying to find a folder which starts with the name 4p. Nothing more

这是否符合您的要求?:

#include <iostream>
#include <vector>
using namespace std;

int
main ()
{
  std::vector < std::string > _strings;
  // adding some elements to iterate over the vector
  _strings.emplace_back ("4p_path");
  _strings.emplace_back ("4p_path1");
  _strings.emplace_back ("3p_path");
  _strings.emplace_back ("4p_path2");
  _strings.emplace_back ("2p_path");
  _strings.emplace_back ("4p_path3");

for (const auto & p:_strings)
    {
      std::string first_two = p.substr (0, 2);// 0 = begin, 2 = end
      if (first_two == std::string ("4p")) // I assume 4p as suffix
    {
      std::cout << "4p\n";
    }
      else
    {
      std::cout << "not 4p\n";
    }
    }

  return 0;
}

既然你说我必须找到具有 4p 后缀的确切文件夹,我应该添加这个:

#include <string>
#include <iostream>
#include <filesystem>
namespace fs = std::filesystem;

int main()
{
    std::vector < std::string > _Folders;
    std::string path = "F:\MyMusicProjects";// your directory
    // get the name of all folders and add it into folders vector
    for (const auto& entry : fs::directory_iterator(path)) {
  _Folders.emplace_back(std::string(entry.path().filename().string()));
    }
    // iterate over folders
    for (const auto& p : _Folders)
    {
        // p variable is the folder name and we compare it to check wheter it starts with 4p or not
        if (p.substr(0, 2) == "4p")
            std::cout << "found\t" << path << "\" << p << "\n";
        else
            std::cout << "was not 4p\t" << path<< "\" << p << "\n";

        // don't forget, p is the folder name, to get full path as string:
        // std::string fullPath = path+"\"+p;
    }
    return 0;
}