Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Example of realpath function in C

Tags:

c

posix

realpath

I'm looking for an example of how to use the realpath function in a C program. I can't seem to find one on the web or in any of my C programming books.

like image 921
Ralph Avatar asked Oct 13 '09 21:10

Ralph


People also ask

What is realpath in C?

The realpath() function derives, from the path name pointed to by file_name, an absolute path name that names the same file, whose resolution does not involve ".","..", or symbolic links. The generated path name is stored, up to a maximum of PATH_MAX bytes, in the buffer pointed to by resolved_name.

What realpath means?

Definition and Usage The realpath() function returns the absolute pathname. This function removes all symbolic links (like '/./', '/../' and extra '/') and returns the absolute pathname.

Does realpath null terminate?

USAGE. The realpath() function operates on null-terminated strings. One should have execute permission on all the directories in the given and the resolved path. The realpath() function may fail to return to the current directory if an error occurs.

What is realpath in shell script?

The realpath command expands all symbolic links and resolves references to /./, /../ and extra '/' characters in the null-terminated string named by path to produce a canonicalized absolute pathname.


1 Answers

  • Note

    • The realpath() function is not described in the C Standard
      • It is however described by POSIX 1997 and POSIX 2008.
  • Sample Code

#include <limits.h> /* PATH_MAX */
#include <stdio.h>
#include <stdlib.h>

int main(void) {
    char buf[PATH_MAX]; /* PATH_MAX incudes the \0 so +1 is not required */
    char *res = realpath("this_source.c", buf);
    if (res) { // or: if (res != NULL)
        printf("This source is at %s.\n", buf);
    } else {
        char* errStr = strerror(errno);
        printf("error string: %s\n", errStr);

        perror("realpath");
        exit(EXIT_FAILURE);
    }
    return 0;
}
  • Reference
    • PATH_MAX defined in PATH_MAX from POSIX 1997
    • errno
    • strerror
like image 144
pmg Avatar answered Sep 20 '22 18:09

pmg