Home > Software design >  Check if folders name starts with certain string
Check if folders name starts with certain string

Time:02-15

Hello so basically what i want is to loop through all folders in a given directory and find a folder which contains 4p in it´s name

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

But this code does not work

CodePudding user response:

Since you told:

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

Does this meet your demands?:

#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;
}

Since you said that I have to find exact folders that have 4p suffixes, I should add this one:

#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().string().substr(path.size() 1,entry.path().string().size())));
    }
    // 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;
}
  • Related