following symbolic links in C
Asked Answered
C

4

10

I'm looking to write a C program which, given the name of symbolic link, will print the name of the file or directory the link points to. Any suggestions on how to start?

Conwell answered 14/10, 2009 at 22:40 Comment(2)
what platform are you doing this on? On Windows it involves Win32 code, on linux obviously something different.Skinflint
Do I detect the faint smell of homework? (-:Clingy
P
9

Make sure that you have an environment which supports POSIX functions, include unistd.h and then use the readlink function.

Pannikin answered 14/10, 2009 at 22:47 Comment(0)
V
11

The readlink() function that has been mentioned is part of the answer. However, you should be aware of its horrid interface (it does not null terminate the response string!).

You might also want to look at the realpath() function, the use of which was discussed in SO 1563186. You could also look at the code for 'linkpath' at the IIUG Software Archive. It analyzes the security of all the directories encountered as a symbolic link is resolved - it uses readlink() and lstat() and stat(); one of the checks when testing the program was to ensure that realpath() resolved the name to the same file.

Vasodilator answered 14/10, 2009 at 23:1 Comment(0)
P
9

Make sure that you have an environment which supports POSIX functions, include unistd.h and then use the readlink function.

Pannikin answered 14/10, 2009 at 22:47 Comment(0)
P
1

Depending on the platform, stat() or fstat() are probably the first things to try out. If you're on Linux or cygwin then the stat program will give you a reasonable idea of what to expect from the system API call (it pretty much gives you a text dump of it).

Psychochemical answered 14/10, 2009 at 22:45 Comment(1)
stat, fstat and lstat will give you details of files a links, such as modification times, but won't tell you what a link points to.Pannikin
E
1

The system call you want is readlink(). Takes a path to the link, returns the string (not always a valid path in the filesystem!) stored in the link. Check the man page ("man 2 readlink") for details.

Note there is some ambiguity to your question. You might be asking for how to tell the "real" path in the filesystem, which is a little more complicated.

Edouard answered 14/10, 2009 at 22:47 Comment(2)
as complicated as calling "realpath()"?Bedad
Well, yeah. I meant the link-expansion algorithm is more complicated than a single system call. As others have posited, this looks like a homework assignment. I don't think a library call is likely to be an acceptable assignment solution. :)Edouard

© 2022 - 2024 — McMap. All rights reserved.