1/* addext.c -- add an extension to a file name 2 Copyright (C) 1990, 1997-1999, 2001-2003, 2005-2006 Free Software Foundation, Inc. 3 4 This program is free software: you can redistribute it and/or modify 5 it under the terms of the GNU General Public License as published by 6 the Free Software Foundation; either version 3 of the License, or 7 (at your option) any later version. 8 9 This program is distributed in the hope that it will be useful, 10 but WITHOUT ANY WARRANTY; without even the implied warranty of 11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 GNU General Public License for more details. 13 14 You should have received a copy of the GNU General Public License 15 along with this program. If not, see <http://www.gnu.org/licenses/>. */ 16 17/* Written by David MacKenzie <djm@gnu.ai.mit.edu> and Paul Eggert */ 18 19#include <config.h> 20 21#ifndef HAVE_DOS_FILE_NAMES 22# define HAVE_DOS_FILE_NAMES 0 23#endif 24#ifndef HAVE_LONG_FILE_NAMES 25# define HAVE_LONG_FILE_NAMES 0 26#endif 27 28#include "backupfile.h" 29 30#include <limits.h> 31#ifndef _POSIX_NAME_MAX 32# define _POSIX_NAME_MAX 14 33#endif 34 35#include <sys/types.h> 36#if HAVE_STRING_H 37# include <string.h> 38#else 39# include <strings.h> 40#endif 41 42#include <unistd.h> 43 44#include "basename.h" 45 46/* Append to FILENAME the extension EXT, unless the result would be too long, 47 in which case just append the character E. */ 48 49void 50addext (char *filename, char const *ext, char e) 51{ 52 char *s = basename (filename); 53 size_t slen = strlen (s), extlen = strlen (ext); 54 long slen_max = -1; 55 56#if HAVE_PATHCONF && defined _PC_NAME_MAX 57 if (slen + extlen <= _POSIX_NAME_MAX && ! HAVE_DOS_FILE_NAMES) 58 /* The file name is so short there's no need to call pathconf. */ 59 slen_max = _POSIX_NAME_MAX; 60 else if (s == filename) 61 slen_max = pathconf (".", _PC_NAME_MAX); 62 else 63 { 64 char c = *s; 65 *s = 0; 66 slen_max = pathconf (filename, _PC_NAME_MAX); 67 *s = c; 68 } 69#endif 70 if (slen_max < 0) 71 slen_max = HAVE_LONG_FILE_NAMES ? 255 : 14; 72 73 if (HAVE_DOS_FILE_NAMES && slen_max <= 12) 74 { 75 /* Live within DOS's 8.3 limit. */ 76 char *dot = strchr (s, '.'); 77 if (dot) 78 { 79 slen -= dot + 1 - s; 80 s = dot + 1; 81 slen_max = 3; 82 } 83 else 84 slen_max = 8; 85 extlen = 9; /* Don't use EXT. */ 86 } 87 88 if (slen + extlen <= slen_max) 89 strcpy (s + slen, ext); 90 else 91 { 92 if (slen_max <= slen) 93 slen = slen_max - 1; 94 s[slen] = e; 95 s[slen + 1] = 0; 96 } 97} 98