This is Stack Overflow so I assume you want code:
All following code assumes that you want to create a symbolic link named /tmp/link
that links to /tmp/realfile
.
CAUTION: Although this code checks for errors, it does NOT check if /tmp/realfile
actually exists ! This is because a dead link is still valid and depending on your code you might (rarely) want to create the link before the real file.
Shell (bash, zsh, ...)
#!/bin/sh
ln -s /tmp/realfile /tmp/link
Real simple, just like you would do it on the command line (which is the shell). All error handling is done by the shell interpreter. This code assumes that you have a working shell interpreter at /bin/sh
.
If needed you could still implement your own error handling by using the $?
variable which will only be set to 0 if the link was successfully created.
C and C++
#include
#include
int main () {
if( symlink("/tmp/realfile", "/tmp/link") != 0 )
perror("Can't create the symlink");
}
symlink
only returns 0 when the link can be created. In other cases I'm using perror
to tell more about the problem.
Perl
#!/usr/bin/perl
if( symlink("/tmp/realfile", "/tmp/link") != 1) {
print STDERR "Can't create the symlink: $!\n"
}
This code assumes you have a perl 5 interpreter at /usr/bin/perl
. symlink
only returns 1 if the link can be created. In other cases I'm printing the failure reason to the standard error output.