sbase

suckless unix tools
git clone git@git.2f30.org/sbase.git
Log | Files | Refs | README | LICENSE

readlink.c (846B)


      1 /* See LICENSE file for copyright and license details. */
      2 #include <limits.h>
      3 #include <stdio.h>
      4 #include <stdlib.h>
      5 #include <string.h>
      6 #include <unistd.h>
      7 
      8 #include "util.h"
      9 
     10 static void
     11 usage(void)
     12 {
     13 	eprintf("usage: %s [-fn] path\n", argv0);
     14 }
     15 
     16 int
     17 main(int argc, char *argv[])
     18 {
     19 	char buf[PATH_MAX];
     20 	ssize_t n;
     21 	int nflag = 0, fflag = 0;
     22 
     23 	ARGBEGIN {
     24 	case 'f':
     25 		fflag = ARGC();
     26 		break;
     27 	case 'n':
     28 		nflag = 1;
     29 		break;
     30 	default:
     31 		usage();
     32 	} ARGEND
     33 
     34 	if (argc != 1)
     35 		usage();
     36 
     37 	if (strlen(argv[0]) >= PATH_MAX)
     38 		eprintf("path too long\n");
     39 
     40 	if (fflag) {
     41 		if (!realpath(argv[0], buf))
     42 			eprintf("realpath %s:", argv[0]);
     43 	} else {
     44 		if ((n = readlink(argv[0], buf, PATH_MAX - 1)) < 0)
     45 			eprintf("readlink %s:", argv[0]);
     46 		buf[n] = '\0';
     47 	}
     48 
     49 	fputs(buf, stdout);
     50 	if (!nflag)
     51 		putchar('\n');
     52 
     53 	return fshut(stdout, "<stdout>");
     54 }