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 2, or (at your option)
7   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; see the file COPYING.
16   If not, write to the Free Software Foundation,
17   51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.  */
18
19/* Written by David MacKenzie <djm@gnu.ai.mit.edu> and Paul Eggert */
20
21#include <config.h>
22
23#ifndef HAVE_DOS_FILE_NAMES
24# define HAVE_DOS_FILE_NAMES 0
25#endif
26#ifndef HAVE_LONG_FILE_NAMES
27# define HAVE_LONG_FILE_NAMES 0
28#endif
29
30#include "backupfile.h"
31
32#include <limits.h>
33#ifndef _POSIX_NAME_MAX
34# define _POSIX_NAME_MAX 14
35#endif
36
37#include <sys/types.h>
38#if HAVE_STRING_H
39# include <string.h>
40#else
41# include <strings.h>
42#endif
43
44#include <unistd.h>
45
46#include "basename.h"
47
48/* Append to FILENAME the extension EXT, unless the result would be too long,
49   in which case just append the character E.  */
50
51void
52addext (char *filename, char const *ext, char e)
53{
54  char *s = basename (filename);
55  size_t slen = strlen (s), extlen = strlen (ext);
56  long slen_max = -1;
57
58#if HAVE_PATHCONF && defined _PC_NAME_MAX
59  if (slen + extlen <= _POSIX_NAME_MAX && ! HAVE_DOS_FILE_NAMES)
60    /* The file name is so short there's no need to call pathconf.  */
61    slen_max = _POSIX_NAME_MAX;
62  else if (s == filename)
63    slen_max = pathconf (".", _PC_NAME_MAX);
64  else
65    {
66      char c = *s;
67      *s = 0;
68      slen_max = pathconf (filename, _PC_NAME_MAX);
69      *s = c;
70    }
71#endif
72  if (slen_max < 0)
73    slen_max = HAVE_LONG_FILE_NAMES ? 255 : 14;
74
75  if (HAVE_DOS_FILE_NAMES && slen_max <= 12)
76    {
77      /* Live within DOS's 8.3 limit.  */
78      char *dot = strchr (s, '.');
79      if (dot)
80	{
81	  slen -= dot + 1 - s;
82	  s = dot + 1;
83	  slen_max = 3;
84	}
85      else
86	slen_max = 8;
87      extlen = 9; /* Don't use EXT.  */
88    }
89
90  if (slen + extlen <= slen_max)
91    strcpy (s + slen, ext);
92  else
93    {
94      if (slen_max <= slen)
95	slen = slen_max - 1;
96      s[slen] = e;
97      s[slen + 1] = 0;
98    }
99}
100