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.
相关问题
- Multiple sockets for clients to connect to
- Is shmid returned by shmget() unique across proces
- What is the best way to do a search in a large fil
- glDrawElements only draws half a quad
- Index of single bit in long integer (in C) [duplic
What the
realpath()
function does is tell you the pathname of a file when all symbolic links have been resolved. It is not necessarily an absolute pathname if the value you supply is a relative name, but that depends in part on whether you traverse any symbolic links with absolute names for the link value - if you do, then the output is an absolute name after all. Also, if the relative name traverses up to the root directory (or 'beyond', as in '../../../../../..' when only three levels deep in the directory hierarchy).You may have a 'realpath' program already on your machine. Here's the (non-standard) version I wrote.
I needed it to test some software that was evaluating the security of a path, and needed to be sure my code was evaluating the given path to the same resolved location as
realpath()
does. It would probably be sensible to extend it with a '-a' option to ensure names are mapped to absolute names (by prefixing the result ofgetcwd()
to relative pathnames).(Source for stderr.c, stderr.h can be found online if you know where to look. Or contact me - see my profile.)
The
realpath()
function is not described in the C Standard. It is however described by POSIX 1997 and POSIX 2008. If that is what you mean, here is an example:PATH_MAX is defined in <limits.h> (<limits.h> from POSIX 1997)
One-line build command line
Minimalist but it does the job!
Build
Test
Requirements
<<<
and$' ... \n ... '
Crash
My minimalist one-line command line builds an executable
realpath
that produces aSegmentation fault
when the path does not exist. Instead of writingif
/else
blocs to handle that issue within my answer, I have added below some links to let you have a look on the Busybox implementation ofrealpath
andreadlink
.Busybox implementation
For a more complete source code, have a look on this simple implementation.
Official Git repository
coreutils/realpath.c
coreutils/readlink.c
libbb/xreadlink.c
GitHub mirror repository
coreutils/realpath.c
coreutils/readlink.c
libbb/xreadlink.c
Like this:
Borrowed from here