C,打开相对于可执行文件路径的文件?

发布于 2025-01-02 18:20:17 字数 686 浏览 3 评论 0原文

我想修复一个使用相对路径加载数据文件的旧 C 程序(获取源代码),期望从放置它的目录调用可执行文件,例如 LoadEx("./dataFile", dataFile) ; 当然,从另一个目录调用程序会失败,因为无法加载dataFile

如何修改 C 程序以加载相对于可执行文件目录的 dataFiles

编辑: 我原来的问题变得不适用,因此至少重复: - 如何在 C 中找到可执行文件的位置? - 如何使用相对路径打开文件在Linux 中? - 在没有 /proc/self/exe 的情况下查找当前可执行文件的路径

I want to fix an old C program (got the source) that uses relative paths to load data files, expecting the executable is called from the directory where it is placed, such as LoadEx("./dataFile", dataFile); Of course calling the program from another directory fails since the dataFile cannot be loaded.

How can I modify the C program to load dataFiles relative to the executable's directory?

EDIT:
My original question turned inapplicable and so is a duplicate to at least:
- How do I find the location of the executable in C?
- How to open a file with it's relative path in Linux?
- Finding current executable's path without /proc/self/exe

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

难如初 2025-01-09 18:20:17

为什么你不需要readlink("/proc/self/exe")?这是在 Linux 上查找可执行文件路径的方法。

唯一的其他方法是使用 getenv() 从环境中提取 PATH,并遍历 PATH 目录寻找 argv[0] 的匹配项。第一个选项要容易得多。

或者首先对可执行文件执行 which 并将结果作为命令行参数或类似的 hack 传递,然后编写一个脚本来启动程序。

Why don't you want readlink("/proc/self/exe")? This is the way one finds the executable's path on linux.

The only other way is pull the PATH from the environment with getenv() and walk the PATH directories looking for a match for argv[0]. The first option is much easier.

Or write a script to initiate the program after first doing a which on the executable and passing the result in as a command line argument or some such hack.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文