Example of realpath function in C

c, posix, realpath

Solution

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

Problem

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.

Original source