Search code examples
pythoncsymlink

How to read the content of a symlink as a usual file without resolving it?


A symbolic link is, after all, a file. I wish to open a symbolic link as a plain file, byte by byte, without resolving to the place where it points to. To give an example, git does this; see this answer https://stackoverflow.com/a/954575 for more details

How can I to do this in C or Python?

If I use fopen or open, then the symlink is automatically resolved. How can I change this behaviour?


Solution

  • A symbolic link is, after all, a file.

    In some sense, yes. A symbolic link generally has its own inode, or is presented as if it did, so it is a file in that sense. The same is true of a directory. And of course, in UNIX, everything is a file.

    But a symbolic link is not a regular file. System interfaces that interact with regular-file contents traverse symbolic links to get to the contents of the file or directory, if any, to which they refer.

    I wish to open a symbolic link as a plain file, byte by byte, without resolving to the place where it points to.

    Generally speaking, you can't. Not from user space. The OS kernel of course reads the filesystem structures from storage, including the data of inodes representing symbolic links, but the raw data are not exposed to userspace programs via the system interfaces that provide access to regular-file contents.

    You can, however, use dedicated interfaces for retrieving a string containing the path to which a symlink points. The C library function specified by POSIX for this purpose is readlink(). You may also have realpath() available to you, which will perform full path resolution through possibly-many layers of symlinks to an ultimate file. But neither of these is the same as accessing the data of a symlink as if the symlink were a regular file.

    Python has versions of both of those: os.readlink() and os.path.realpath().