Search code examples
c++implicit-conversion

no suitable conversion function from "const std::filesystem::path" to "char *" exists


I'm a C++ beginner. I've been learning C++ for a week now.

I was messing around with the <filesystem> library, trying to learn new things. I tried to make a function to receive a path to a .txt file and reads the file contents to print it to the console. But, I ran into this problem which is in the title:

using namespace std;
using namespace std::filesystem;

void read_file(char File[260]);

int main(){
    for (auto entry: recursive_directory_iterator("C:\\Users\\malar\\AppData\\Local")){
        try{
            if (entry.path().extension() == ".txt"){
                read_file(entry.path()); // no suitable conversion function from "const std::filesystem::path" to "char *" exists
            }
        }
        catch (filesystem_error){
            continue;
        }
    }
    
    return 0;
}

void read_file(char File[260]){
    FILE *rf = fopen(File, "r"); // rf = read file
    char Buffer[260];
    if (rf == NULL){
        cout << "File: " << File << " Cannot be opened\n";
    }
    while (fread(Buffer, 260, 1, rf) != NULL){
        cout << Buffer << endl;
    }
    fclose(rf);
    cout << "File Closed\n";
}

I've tried to fix the problem by doing type conversion, but perhaps I did it with a wrong type?


Solution

  • Make path::string() first or path::u8string() for UTF-8 to get the path, and then you can use the string::c_str() method.