【问题标题】:How to enable file paths on another system如何在另一个系统上启用文件路径
【发布时间】:2018-09-16 16:13:31
【问题描述】:

我有几个使用这样的路径初始化的文件:

  String filePath = "/Users/user1/Documents/UWE/Year_3/SDA/GDA GUI Test/Program_Files/modelgraphic1.png";

它们显示图像,当在另一台计算机上运行时,图像不会出现。我记得过去做过这样的事情:

  String filePath = "/.../.../.../.../.../.../GDA GUI Test/Program_Files/modelgraphic1.png";

这行不通。我该如何纠正这个问题?非常感谢。

【问题讨论】:

  • 不要使用绝对路径。使用相对路径。通常与可执行文件相关 - 查找 -rpath$ORIGIN 以及“当前工作目录”。

标签: c++ image file filepath


【解决方案1】:

就路径而言,Boost Filesystem 是最依赖的库之一。
Boost 文件系统文档 => https://www.boost.org/doc/libs/1_66_0/libs/filesystem/doc/index.htm

使用理由:

  • 现代 C++ 接口,与 C++ 标准库高度兼容。
  • 操作系统之间的可移植性。
  • 通过 C++ 异常(默认)或错误代码处理和报告错误。

原始答案 => https://stackoverflow.com/a/6297807/2303176
示例代码:

#include <iostream>
#include <boost/filesystem.hpp>

namespace fs = boost::filesystem;

int main ()
{
    fs::path dir ("/tmp");
    fs::path file ("foo.txt");
    fs::path full_path = dir / file;
    std::cout << full_path << std::endl;
}

然后运行它 -

$ g++ ./test.cpp -o test -lboost_filesystem -lboost_system
$ ./test 
/tmp/foo.txt

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-08
    • 1970-01-01
    • 2023-02-20
    • 2012-07-10
    • 2012-04-30
    • 2022-08-17
    相关资源
    最近更新 更多