C,打开相对于可执行文件路径的文件?
我想修复一个使用相对路径加载数据文件的旧 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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
为什么你不需要
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.