1/* 2 File: quote.c 3 4 Copyright (C) 2003 Andreas Gruenbacher <a.gruenbacher@computer.org> 5 6 This program is free software; you can redistribute it and/or 7 modify it under the terms of the GNU Library General Public 8 License as published by the Free Software Foundation; either 9 version 2 of the License, or (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 GNU 14 Library General Public License for more details. 15 16 You should have received a copy of the GNU Library General Public 17 License along with this library; if not, write to the Free Software 18 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. 19*/ 20 21#include <stdio.h> 22#include <stdlib.h> 23#include <ctype.h> 24#include "misc.h" 25 26const char *quote(const char *str) 27{ 28 static char *quoted_str; 29 static size_t quoted_str_len; 30 const unsigned char *s; 31 char *q; 32 size_t nonpr; 33 34 if (!str) 35 return str; 36 37 for (nonpr = 0, s = (unsigned char *)str; *s != '\0'; s++) 38 if (!isprint(*s) || isspace(*s) || *s == '\\') 39 nonpr++; 40 if (nonpr == 0) 41 return str; 42 43 if (high_water_alloc((void **)"ed_str, "ed_str_len, 44 nonpr * 3 + 1)) 45 return NULL; 46 for (s = (unsigned char *)str, q = quoted_str; *s != '\0'; s++) { 47 if (!isprint(*s) || isspace(*s) || *s == '\\') { 48 *q++ = '\\'; 49 *q++ = '0' + ((*s >> 6) ); 50 *q++ = '0' + ((*s >> 3) & 7); 51 *q++ = '0' + ((*s ) & 7); 52 } else 53 *q++ = *s; 54 } 55 *q++ = '\0'; 56 57 return quoted_str; 58} 59