【问题标题】:How to get full path of the file having file name in c++ (linux)如何在c ++(linux)中获取具有文件名的文件的完整路径
【发布时间】:2019-07-06 11:26:43
【问题描述】:

我正在尝试使用 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 命令试过了吗?
  • realpath 打印路径,但它只能在 bash 中正常工作 - 在 cpp system() 中不要将此路径作为字符串返回

标签: c++ system ros yaml-cpp


【解决方案1】:

正如我在评论中所说,我相信您可以使用 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;
}

这取自How do I execute a command and get output of command within C++ using POSIX?

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

【讨论】:

  • 如果这个命令不在包含这个文件的目录中执行呢?
  • 嗯,有很多可能性。我向您展示了如何执行命令并获取其输出。所以现在你可以调用 find 命令或其他东西......它应该可以工作。这也可以帮助你:askubuntu.com/questions/444551/…
猜你喜欢
  • 1970-01-01
  • 2014-09-26
  • 1970-01-01
  • 2011-04-19
  • 1970-01-01
  • 2014-06-08
  • 1970-01-01
  • 1970-01-01
  • 2011-07-14
相关资源
最近更新 更多