繁体   English   中英

如何在C ++(Linux)中获取具有文件名的文件的完整路径

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

我正在尝试使用yaml-cpp解析yaml文件,但它需要file.yaml的完整路径。 如果该路径可能因用户设置而有所不同,我应该如何获得它。 我假设这个文件名不会改变

这是针对ROS动力学框架的,因此它在Linux上运行。 我已经尝试使用system()函数获取此路径,但是它没有返回字符串。

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

正如我在评论中所说,我相信您可以使用realpath做到这一点。 如您所说,这是bash命令。 但是,您可以像这样执行

#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;
}

或与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;
}

这取自于我如何使用POSIX在C ++中执行命令并获得命令输出?

我只在这里复制了代码,所以内容也在这里。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM