如何在C Linux中将绝对路径转换为相对路径

我想知道如何在Linux(Ubuntu)OS上使用c语言基于给定目录(包括链接文件)将符号链接的绝对路径转换为相对路径.

I would like to know how an absolute path of a symbolic link can be converted to relative based on a given directory (that includes the linked file) in c language on linux (Ubuntu) OS.

我想搜索相对路径的子字符串,但是如果它已经存在于文件夹的层次结构中怎么办?

I thought searching for the sub-string of the relative path, but what if it already exists higher in the folder's hierarchy?

以下是我要执行的操作的更具体说明: 相对路径:

Here is a more specific description of what I want to do: Relative path:

 folder/folder1/folder2

绝对路径:

/home/giorgos/Desktop/folder/folder1/folder2/a.pdf

更改为

/home/giorgos/Desktop/myfolder/folder1/folder2/a.pdf

显然,我不能简单地搜索并替换"folder/",请考虑这种情况:

Obviously I cant' simply search for and replace "folder/", consider this case:

/home/giorgos/Desktop/folder/folder/folder/folder1/folder2/a.pdf

它可以向前和向后搜索,如果被替换,它仍然给出错误的输出 只有当我知道相对路径时,我才能向后搜索绝对值并将其替换,然后输出才是正确的:

It can be searched both forwards and backwards and if replaced it still gives a wrong output Only if I knew the relative path I could search the absolute backwards and replace it, then the output would be correct:

   /home/giorgos/Desktop/folder/myfolder/folder/folder1/folder2/a.pdf



 1 条回答