Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Directory iterator value as variable

Tags:

c++

I am trying to transfer output of std:filesystem directory_iterator to vector or variable. Keep getting error: no operator "=" matches these operands -- operand types are: std::string = const std::filesystem

I am realively new to C++ and hit the wall at this point. Previously I have been using system commands but would like to avoid it in the future.

#include <string>
#include <iostream>
#include <filesystem>
#include <vector>
namespace fs = std::filesystem;
using namespace std;
int main()
{
    string objectInDirectory = "Jabberwocky";
    string dirlisted = "";
    for (const auto & entry : fs::directory_iterator(dirlisted)) {
        cout << "Next directory entry: " << entry.path() << endl;
        objectInDirectory = entry.path();
    }
    getchar();
}
like image 430
mismichael Avatar asked Nov 26 '25 19:11

mismichael


1 Answers

entry.path() returns a const std::filesystem::path&. This is not implicitly convertible to std::string, so you need to call its string function:

 objectInDirectory = entry.path().string();

Conversion to string is not necessary; you could assign it to a std::filesystem::path instead without needing a conversion. This can be more ideal because there are better built-in path-manipulation tools for std::filesystem::path than std::string

like image 127
AndyG Avatar answered Nov 29 '25 09:11

AndyG



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!