Getting absolute path of a file
Use realpath().
The
realpath()
function shall derive, from the pathname pointed to byfile_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 byresolved_name
.If
resolved_name
is a null pointer, the behavior ofrealpath()
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);
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);
}
There is also a small path library cwalk which works cross-platform. It has cwk_path_get_absolute to do that:
#include <cwalk.h>
#include <stdio.h>
#include <stddef.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
char buffer[FILENAME_MAX];
cwk_path_get_absolute("/hello/there", "./world", buffer, sizeof(buffer));
printf("The absolute path is: %s", buffer);
return EXIT_SUCCESS;
}
Outputs:
The absolute path is: /hello/there/world