Name

realpath - returns the canonicalized absolute pathname

Library

libc.lib

Synopsis

  #include <sys/param.h>
  #include <stdlib.h>
  char * realpath (const char *pathname, char resolved_path[PATH_MAX]);

Return values

The realpath function returns resolved_path on success. If an error occurs, realpath returns NULL, and resolved_path contains the pathname which caused the problem.

Detailed description

The realpath function resolves all symbolic links, extra "/" characters and references to /./ and /../ in pathname, and copies the resulting absolute pathname into the memory referenced by resolved_path. The resolved_path argument must refer to a buffer capable of storing at least PATH_MAX characters.

The realpath function will resolve both absolute and relative paths and return the absolute pathname corresponding to pathname. All but the last component of pathname must exist when realpath is called.


Examples

#include<stdlib.h>
#include<stdio.h> //printf
#include<sys/stat.h> //S_IWUSR
#include<sys/syslimits.h> //PATH_MAX
#include<unistd.h> //chdir
 
int main()
{
 char resolvepath[PATH_MAX];
 FILE *fp = NULL;
 char *rpath = NULL;
 int isymlink = 0;
  
 fp = fopen("c:\\xyz.txt", "w");
 if(!fp)
 {
     printf("fopen failed!!");
     return -1;
 }
    
 mkdir("c:\\tmdir", S_IWUSR);
  
 int c = chdir("c:\\");
 if(c == -1)
 {
     printf("chdir failed!!");
     return -1;
 }
  
 rpath = realpath(".\\tmdir\\..\\xyz.txt", resolvepath);
 printf("resolvepath: %s\n", resolvepath);
 if(rpath != NULL)
    printf("rpath: %s\n\n", rpath);
  
 fclose(fp);
 rmdir("c:\\tmdir");
 unlink("c:\\xyz.txt");
  
 mkdir("c:\\tdir", S_IWUSR);
  
 fp = fopen("c:\\tdir\\xyz.txt", "w");
 if(!fp)
 {
     printf("fopen failed!!");
     return -1;
 }
  
 fclose(fp);
  
 unlink("c:\\linkname.txt");
    
 isymlink = symlink("c:\\tdir\\xyz.txt", "c:\\linkname.txt");
 if (isymlink == -1)
 {
     printf("symlink failed!!");
     return -1;
 }
   
 rpath = realpath("c:\\linkname.txt", resolvepath);
  
 printf("resolvepath: %s\n", resolvepath);
 if(rpath != NULL)
    printf("rpath: %s\n", rpath);
  
 unlink("c:\\tdir\\xyz.txt");
 rmdir("c:\\tdir");
   
 return 0;
}

         

Output

resolvepath: C:\xyz.txt
rpath: C:\xyz.txt
resolvepath: c:\tdir\xyz.txt
rpath: c:\tdir\xyz.txt

         

Security considerations

The realpath has Off-by-One Overflow.If possible the user must supply a specially crafted pathname that is 1024 characters in length to the realpath function. A buffer can be overwritten with a single byte (NULL) if the pathname contains two or more directory separators.

This function may permit buffer overflow depeding upon its user.


Errors

The function realpath may fail and set the external variable errno for any of the errors specified for the library functions readlink and getcwd.

See also

getcwd

Feedback

For additional information or queries on this page send feedback

© 2005-2007 Nokia

Top