Search code examples
c++systemrosyaml-cpp

How to get full path of the file having file name in c++ (linux)


I'm trying to parse yaml file using yaml-cpp but it needs full path of file.yaml . How should I get this path if it can be different depending on user setup. I'm assuming that this filename wont change

This is for ROS kinetic framework so it's running on linux. I've already tried to get this path using system() function but it's not returning string.

string yaml_directory = system("echo 'find -name \"file.yaml\"' ") ; // it's not working as expected 
YAML::Node conf_file = YAML::LoadFile("/home/user/path/path/file.yaml"); //I want to change from that string to path found automatically

Solution

  • As I said in comment I believe you can do this with realpath. As you stated, this is bash command. However, you can execute this like this

    #include <iostream>
    #include <stdexcept>
    #include <stdio.h>
    #include <string>
    
    std::string exec(const char* cmd) {
        char buffer[128];
        std::string result = "";
        FILE* pipe = popen(cmd, "r");
        if (!pipe) throw std::runtime_error("popen() failed!");
        try {
            while (fgets(buffer, sizeof buffer, pipe) != NULL) {
                result += buffer;
            }
        } catch (...) {
            pclose(pipe);
            throw;
        }
        pclose(pipe);
        return result;
    }
    

    or with C++11

    #include <cstdio>
    #include <iostream>
    #include <memory>
    #include <stdexcept>
    #include <string>
    #include <array>
    
    std::string exec(const char* cmd) {
        std::array<char, 128> buffer;
        std::string result;
        std::unique_ptr<FILE, decltype(&pclose)> pipe(popen(cmd, "r"), pclose);
        if (!pipe) {
            throw std::runtime_error("popen() failed!");
        }
        while (fgets(buffer.data(), buffer.size(), pipe.get()) != nullptr) {
            result += buffer.data();
        }
        return result;
    }
    

    This was taken from How do I execute a command and get output of command within C++ using POSIX?

    I only copied code here so that content is also here.