Migrated from GPL version 2 to GPL version 3
[findutils.git] / lib / printquoted.c
blobaa2c3a4ef00b39065558c4f82efe82efb58c5045
1 /* printquoted.c -- print a specified string with any necessary quoting.
3 Copyright (C) 1990, 1991, 1992, 1993, 1994, 2000,
4 2003, 2004, 2005 Free Software Foundation, Inc.
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.
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.
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/>.
20 #include <config.h>
23 #include <stddef.h>
24 #include <stdlib.h>
25 #include <stdio.h>
27 /* Get mbstate_t, mbrtowc(), mbsinit(), wcwidth(). */
28 #if HAVE_WCHAR_H
29 # include <wchar.h>
30 #endif
34 #include "xalloc.h"
35 #include "printquoted.h"
39 * Print S according to the format FORMAT, but if the destination is a tty,
40 * convert any potentially-dangerous characters. The logic in this function
41 * was taken from ls.c in coreutils (at Sun Jun 5 20:42:51 2005 UTC).
43 int
44 print_quoted (FILE *fp,
45 const struct quoting_options *qopts,
46 bool dest_is_tty,
47 const char *format,
48 const char *s)
50 int rv;
52 if (dest_is_tty)
54 char smallbuf[BUFSIZ];
55 size_t len = quotearg_buffer (smallbuf, sizeof smallbuf, s, -1, qopts);
56 char *buf;
57 if (len < sizeof smallbuf)
58 buf = smallbuf;
59 else
61 /* The original coreutils code uses alloca(), but I don't
62 * want to take on the anguish of introducing alloca() to
63 * 'find'.
64 * XXX: newsflash: we already have alloca().
66 buf = xmalloc (len + 1);
67 quotearg_buffer (buf, len + 1, s, -1, qopts);
70 /* Replace any remaining funny characters with '?'. */
71 len = qmark_chars(buf, len);
73 rv = fprintf(fp, format, buf); /* Print the quoted version */
74 if (buf != smallbuf)
76 free(buf);
77 buf = NULL;
80 else
82 /* no need to quote things. */
83 rv = fprintf(fp, format, s);
85 return rv;