jeudi 3 août 2023

How to open a file with unknown path in C++?

So I am writing an implementation of a Markov Model in C++ for my university. I'am almost done but I'm missing one last step which is writing a function that opens the given input file, opening on my pc is easy I just need to specify the path but when I will submit my code the path is not going to be the same. How can I modify the function I wrote in order to do that?

std::ifstream* open_test (std::string filename) {
    
    //std::cout << "Opening test file" << std::endl;
    std::ifstream* file = new std::ifstream;
    std::string path = "./materials/tests/";

    std::string full_path = path + filename;
    //std::cout << full_path << std::endl;

    file->open (full_path, std::ios::in);

    if (!file) {
        delete file;
        throw std::runtime_error("ERROR: Couldn't open file'");
    }
    else {
        //std::cout << "File opened successfully" << std::endl;
        return file;
    }

} 

Thanks in advance

I tried replacing full_path with filename but of course it does not work.

Aucun commentaire:

Enregistrer un commentaire