LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Is it possible to open a symlink (won't follow) and read data from it? (https://www.linuxquestions.org/questions/programming-9/is-it-possible-to-open-a-symlink-wont-follow-and-read-data-from-it-843372/)

lesca 11-09-2010 11:51 PM

Is it possible to open a symlink (won't follow) and read data from it?
 
I try to use open(2) system call, and I find one relevant flag: O_NOFOLLOW. But it will only return -1 rather than the symlink's file descriptor.

Can anyone give me some tips?

Thanks!

neonsignal 11-10-2010 12:31 AM

You can use lstat to determine if it is a symbolic link. If it is, then you can use readlink to read the contents.

The O_NOFOLLOW flag on open causes a deliberate failure (which is useful for programs that need to recurse through subdirectories).

lesca 11-10-2010 02:29 AM

But how can I read data from symlink itself?

gnashley 11-10-2010 03:09 AM

A symlink doesn't contain any data. It consists only of meta-data and is theoretically of size 0 bytes. Anything you need to know about the link can be gotten using 'lstat'.

lesca 11-10-2010 04:40 AM

I see. But lstat only provide me with its state data.

And how can I know which file it links to?
I think I need to read its metadata, but which function can do this?

neonsignal 11-10-2010 06:08 AM

Quote:

Originally Posted by lesca (Post 4154478)
But how can I read data from symlink itself?

See my first reply above, use readlink.

Quote:

Originally Posted by man 2 readlink
Name

readlink - read value of a symbolic link

Synopsis

#include <unistd.h>

ssize_t readlink(const char *path, char *buf, size_t bufsiz);

Description

readlink() places the contents of the symbolic link path in the buffer buf, which has size bufsiz. readlink() does not append a null byte to buf. It will truncate the contents (to a length of bufsiz characters), in case the buffer is too small to hold all of the contents.

Return Value

The call returns the count of characters placed in the buffer if it succeeds, or a -1 if an error occurs, placing the error code in errno.

...



All times are GMT -5. The time now is 05:26 AM.