Home > Mobile >  When I run the code, the system gives two error warnings, I wonder what is causing this?
When I run the code, the system gives two error warnings, I wonder what is causing this?

Time:01-30

#include <string>
#include <filesystem>
#include <iomanip>
#include <iostream>
#include <regex>

namespace fs = std::filesystem;

using namespace std;

int main(int argc, char *argv[]) {
   
   if (argc != 2 && argc != 3) {  
       cerr << "Usage: " << argv[0] << " <path> [<regex>]\n";  
       return 1;
   }
   
   fs::path const base = argv[1];
   char const* re = ".*";
   regex compiled_re(re);
   
   for(auto const& entry : fs::recursive_directory_iterator(base,fs::directory_options::skip_permission_denied)) {
       smatch m;
       if (regex_match(entry.path().filename().native(), m, compiled_re)) {
           string const s = entry.path().lexically_relative(base).native();
           if (fs::is_symlink(entry)) {
               cout << "LINK: " << quoted(s) << '\n';
           }
           else if (fs::is_regular_file(entry)) {
               cout << "FILE: " << fs::file_size(entry) << ' ' << quoted(s) << '\n';
           }
           else if (fs::is_directory(entry)) {
               cout << "DIR: " << quoted(s) << '\n';
           }
           else {
               cout << "OTHER: " << quoted(s) << '\n';
           }
       }
   }
   return 0;
}

when i run the code, it have two error

no matching function for call to 'regex_match(const std::filesystem::__cxx11::path::string_type&, std::__cxx11::smatch&, std::__cxx11::regex&)'

conversion from 'basic_string<wchar_t>' to non-scalar type 'basic_string' requested

What causes these errors to appear?

CodePudding user response:

You are compiling the code on Windows, correct?

On this platform, std::filesystem::path::native() returns a std::wstring. But you are using narrow string regex – that doesn't fit together. You can should probably switch to using wide-string regex:

   wchar_t const* re = L".*";
   wregex compiled_re(re);
   
   for(auto const& entry : fs::recursive_directory_iterator(base,fs::directory_options::skip_permission_denied)) {
       wsmatch m;
       if (regex_match(entry.path().filename().native(), m, compiled_re)) {
           wstring const s = entry.path().lexically_relative(base).native();

But you can't pass these wide string to cout either, but you can fix that by using wcout instead of cout

  •  Tags:  
  • c
  • Related