0

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
Adam Krawczyk
  • 71
  • 1
  • 5

1 Answers1

0

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.

golobitch
  • 1,466
  • 3
  • 19
  • 38
  • how about if this command is not executed in directory containing this file? – Adam Krawczyk Jul 06 '19 at 13:02
  • Well, there are many possiblities. I showed you how to execute command and get its output. So now you can call find command or something else...and it should work. This can also help you: https://askubuntu.com/questions/444551/get-absolute-path-of-files-using-find-command – golobitch Jul 06 '19 at 13:19