如何在Linux中使用相对路径打开文件? [英] How to open a file with it's relative path in Linux?

查看:1162
本文介绍了如何在Linux中使用相对路径打开文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用相对路径(例如'..')打开文件的程序.

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

现在的问题是,当我从另一个目录执行程序时,相对路径不是相对于程序而是相对于工作目录.因此,如果我使用"/path/to/program/myprog"启动程序,它将无法找到该文件.

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?

推荐答案

如果程序不是自己做的,那就是一个不好的程序.错误的程序应使用一些Bash脚本进行包装:

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 $*

上面的脚本确定了该目录所在的目录,然后将当前工作目录更改为该目录,并从该目录运行程序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.

假定您有权访问源代码并且可以修复该程序,然后使用 proc fs 确定程序的位置,然后使用绝对路径.

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.

例如,/proc/self/exe将始终是指向当前进程的二进制文件的符号链接.使用 readlink 读取其值,然后剪切可执行文件的名称,便得到了目录.

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.

这篇关于如何在Linux中使用相对路径打开文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆