Imported Upstream version 4.5.14
[platform/upstream/findutils.git] / lib / printquoted.c
1 /* printquoted.c -- print a specified string with any necessary quoting.
2
3    Copyright (C) 1990, 1991, 1992, 1993, 1994, 2000, 2003, 2004, 2005,
4    2007, 2009, 2010, 2011 Free Software Foundation, Inc.
5
6    This program is free software: you can redistribute it and/or modify
7    it under the terms of the GNU General Public License as published by
8    the Free Software Foundation, either version 3 of the License, or
9    (at your option) any later version.
10
11    This program is distributed in the hope that it will be useful,
12    but WITHOUT ANY WARRANTY; without even the implied warranty of
13    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14    GNU General Public License for more details.
15
16    You should have received a copy of the GNU General Public License
17    along with this program.  If not, see <http://www.gnu.org/licenses/>.
18 */
19 /* config.h must be included first. */
20 #include <config.h>
21
22 /* system headers. */
23 #include <stdio.h>
24 #include <stdlib.h>
25
26 /* gnulib headers. */
27 #include "xalloc.h"
28
29 /* find headers. */
30 #include "printquoted.h"
31
32 /*
33  * Print S according to the format FORMAT, but if the destination is a tty,
34  * convert any potentially-dangerous characters.  The logic in this function
35  * was taken from ls.c in coreutils (at Sun Jun  5 20:42:51 2005 UTC).
36  */
37 int
38 print_quoted (FILE *fp,
39               const struct quoting_options *qopts,
40               bool dest_is_tty,
41               const char *format,
42               const char *s)
43 {
44   int rv;
45
46   if (dest_is_tty)
47     {
48       char smallbuf[BUFSIZ];
49       size_t len = quotearg_buffer (smallbuf, sizeof smallbuf, s, -1, qopts);
50       char *buf;
51       if (len < sizeof smallbuf)
52         buf = smallbuf;
53       else
54         {
55           /* The original coreutils code uses alloca(), but I don't
56            * want to take on the anguish of introducing alloca() to
57            * 'find'.
58            * XXX: newsflash: we already have alloca().
59            */
60           buf = xmalloc (len + 1);
61           quotearg_buffer (buf, len + 1, s, -1, qopts);
62         }
63
64       /* Replace any remaining funny characters with '?'. */
65       len = qmark_chars (buf, len);
66
67       rv = fprintf (fp, format, buf);   /* Print the quoted version */
68       if (buf != smallbuf)
69         {
70           free (buf);
71           buf = NULL;
72         }
73     }
74   else
75     {
76       /* no need to quote things. */
77       rv = fprintf (fp, format, s);
78     }
79   return rv;
80 }