*** empty log message ***
[gnulib.git] / lib / xreadlink.c
1 /* exclude.c -- exclude file names
2
3    Copyright 2001 Free Software Foundation, Inc.
4
5    This program is free software; you can redistribute it and/or modify
6    it under the terms of the GNU General Public License as published by
7    the Free Software Foundation; either version 2, or (at your option)
8    any later version.
9
10    This program is distributed in the hope that it will be useful,
11    but WITHOUT ANY WARRANTY; without even the implied warranty of
12    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13    GNU General Public License for more details.
14
15    You should have received a copy of the GNU General Public License
16    along with this program; see the file COPYING.
17    If not, write to the Free Software Foundation,
18    59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.  */
19
20 /* Written by Jim Meyering <jim@meyering.net>  */
21
22 #if HAVE_CONFIG_H
23 # include <config.h>
24 #endif
25
26 #include <stdio.h>
27 #if HAVE_SYS_TYPES_H
28 # include <sys/types.h>
29 #endif
30 #if HAVE_STDLIB_H
31 # include <stdlib.h>
32 #endif
33 #if HAVE_UNISTD_H
34 # include <unistd.h>
35 #endif
36
37 #include "xalloc.h"
38 #include "xreadlink.h"
39
40 /* Call readlink to get the symbolic link value of FILENAME.
41    Return a pointer to that NUL-terminated string in malloc'd storage.
42    If readlink fails, return NULL (use errno to diagnose).
43    If realloc fails, or if the link value is longer than SIZE_MAX :-),
44    give a diagnostic and exit.  */
45
46 char *
47 xreadlink (char const *filename, size_t *link_length_arg)
48 {
49   size_t buf_size = 128;  /* must be a power of 2 */
50   char *buffer = NULL;
51
52   while (1)
53     {
54       int link_length;
55       buffer = (char *) xrealloc (buffer, buf_size);
56       link_length = readlink (filename, buffer, buf_size);
57       if (link_length < 0)
58         {
59           free (buffer);
60           return NULL;
61         }
62       if (link_length < buf_size)
63         {
64           *link_length_arg = link_length;
65           buffer[link_length] = 0;
66           return buffer;
67         }
68       buf_size *= 2;
69       if (buf_size == 0)
70         xalloc_die ();
71     }
72 }