linux中find相对路径_如何在Linux中使用相对路径打开文件?

I have a program which opens a file by using a relative path (for instance '..').

Now the problem is, when I execute the program from another directory, the relative path is not relative to the program but relative to the working directory. Thus, if I start the program with '/path/to/program/myprog' it fails to find the file.

Is there a way to execute the program independently of the working directory? Id est, as If the working directory were the directory where the program is located? Or am I just thinking in a too complicated way and there is a much easier way to refer to a file, which location is only known by its path relative to the path of the program file?

解决方案

If program is not doing it by itself, it is a bad program. Bad programs should be wrapped with a bit of Bash scripting:

#!/bin/bash

set -e

cd $(readlink -f $(dirname $0))

exec ./myprog $*

The script above determines the directory where it is located, then changes current working directory to that directory and runs a program myprog from there, passing all parameters transparently. Thus, you have to put this script into the same directory where your program is located and run it instead of your program.

Assuming that you have the access to the source code and can fix the program, then use proc fs to determine the program's location and then use absolute path.

For example, /proc/self/exe will always be a symlink pointing at the binary file of the current process. Use readlink to read its value, then cut executable name and you got the directory.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值