Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting absolute path of a file

How can I convert a relative path to an absolute path in C on Unix? Is there a convenient system function for this?

On Windows there is a GetFullPathName function that does the job, but I didn't find something similar on Unix...

like image 445
evgenka Avatar asked Oct 23 '08 08:10

evgenka


People also ask

How do you get the absolute path of a file in Linux?

To obtain the full path of a file, we use the readlink command. readlink prints the absolute path of a symbolic link, but as a side-effect, it also prints the absolute path for a relative path. In the case of the first command, readlink resolves the relative path of foo/ to the absolute path of /home/example/foo/.

How do I get the absolute path of a file in Python?

Use abspath() to Get the Absolute Path in Python To get the absolute path using this module, call path. abspath() with the given path to get the absolute path. The output of the abspath() function will return a string value of the absolute path relative to the current working directory.

How do I find absolute path in bash?

In this case, first, we need the current script's path, and from it, we use dirname to get the directory path of the script file. Once we have that, we cd into the folder and print the working directory. To get the full or absolute path, we attach the basename of the script file to the directory path or $DIR_PATH.


2 Answers

Use realpath().

The realpath() function shall derive, from the pathname pointed to by file_name, an absolute pathname that names the same file, whose resolution does not involve '.', '..', or symbolic links. The generated pathname shall be stored as a null-terminated string, up to a maximum of {PATH_MAX} bytes, in the buffer pointed to by resolved_name.

If resolved_name is a null pointer, the behavior of realpath() is implementation-defined.


The following example generates an absolute pathname for the file identified by the symlinkpath argument. The generated pathname is stored in the actualpath array.

#include <stdlib.h> ... char *symlinkpath = "/tmp/symlink/file"; char actualpath [PATH_MAX+1]; char *ptr;   ptr = realpath(symlinkpath, actualpath); 
like image 58
xsl Avatar answered Oct 24 '22 22:10

xsl


Try realpath() in stdlib.h

char filename[] = "../../../../data/000000.jpg"; char* path = realpath(filename, NULL); if(path == NULL){     printf("cannot find file with name[%s]\n", filename); } else{     printf("path[%s]\n", path);     free(path); } 
like image 39
Scott Yang Avatar answered Oct 25 '22 00:10

Scott Yang