Example of realpath function in C

前端 未结 4 828
忘掉有多难
忘掉有多难 2020-12-09 17:49

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.

4条回答
  •  离开以前
    2020-12-09 18:08

    One-line build command line

    Minimalist but it does the job!

    Build

    gcc -o realpath -x c - <<< $'#include\n#include\nint main(int c,char**v){puts(realpath(v[1],0));}'
    

    Test

    $> ./realpath  ~/../../../usr/./bin/./awk
    /bin/gawk 
    
    $> readlink -f ~/../../../usr/./bin/./awk
    /bin/gawk
    

    Requirements

    • gcc for compilation and link
    • bash for <<< and $' ... \n ... '

    Crash

    My minimalist one-line command line builds an executable realpath that produces a Segmentation fault when the path does not exist. Instead of writing if/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 of realpath and readlink.


    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

提交回复
热议问题