Debian Codegraph @

listings/chapter-8/print-symlink.c

raw
1 /***********************************************************************
2 * Code listing from "Advanced Linux Programming," by CodeSourcery LLC *
3 * Copyright (C) 2001 by New Riders Publishing *
4 * See COPYRIGHT for license information. *
5 ***********************************************************************/
6
7 #include <errno.h>
8 #include <stdio.h>
9 #include <unistd.h>
10
11 int main (int argc, char* argv[])
12 {
13 char target_path[256];
14 char* link_path = argv[1];
15
16 /* Attempt to read the target of the symbolic link. */
17 int len = readlink (link_path, target_path, sizeof (target_path) - 1);
18
19 if (len == -1) {
20 /* The call failed. */
21 if (errno == EINVAL)
22 /* It's not a symbolic link; report that. */
23 fprintf (stderr, "%s is not a symbolic link\n", link_path);
24 else
25 /* Some other problem occurred; print the generic message. */
26 perror ("readlink");
27 return 1;
28 }
29 else {
30 /* NUL-terminate the target path. */
31 target_path[len] = '\0';
32 /* Print it. */
33 printf ("%s\n", target_path);
34 return 0;
35 }
36 }