.
[coreutils.git] / lib / addext.c
blobfff64f7c7b7ba75f44fbbbb7fcab711517483fd2
1 /* addext.c -- add an extension to a file name
3 Copyright (C) 1990, 1997, 1998, 1999, 2001, 2003 Free Software
4 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 2, or (at your option)
9 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; see the file COPYING.
18 If not, write to the Free Software Foundation,
19 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */
21 /* Written by David MacKenzie <djm@gnu.ai.mit.edu> and Paul Eggert */
23 #if HAVE_CONFIG_H
24 # include <config.h>
25 #endif
27 #ifndef HAVE_DOS_FILE_NAMES
28 # define HAVE_DOS_FILE_NAMES 0
29 #endif
30 #ifndef HAVE_LONG_FILE_NAMES
31 # define HAVE_LONG_FILE_NAMES 0
32 #endif
34 #include <limits.h>
35 #ifndef _POSIX_NAME_MAX
36 # define _POSIX_NAME_MAX 14
37 #endif
39 #include <stddef.h>
40 #include <string.h>
42 #if HAVE_UNISTD_H
43 # include <unistd.h>
44 #endif
46 #include <errno.h>
47 #ifndef errno
48 extern int errno;
49 #endif
51 #include "backupfile.h"
52 #include "dirname.h"
54 /* Append to FILENAME the extension EXT, unless the result would be too long,
55 in which case just append the character E. */
57 void
58 addext (char *filename, char const *ext, int e)
60 char *s = base_name (filename);
61 size_t slen = base_len (s);
62 size_t extlen = strlen (ext);
63 size_t slen_max = HAVE_LONG_FILE_NAMES ? 255 : _POSIX_NAME_MAX;
65 #if HAVE_PATHCONF && defined _PC_NAME_MAX
66 if (_POSIX_NAME_MAX < slen + extlen || HAVE_DOS_FILE_NAMES)
68 /* The new base name is long enough to require a pathconf check. */
69 long name_max;
70 errno = 0;
71 if (s == filename)
72 name_max = pathconf (".", _PC_NAME_MAX);
73 else
75 char c = *s;
76 if (! ISSLASH (c))
77 *s = 0;
78 name_max = pathconf (filename, _PC_NAME_MAX);
79 *s = c;
81 if (0 <= name_max || errno == 0)
83 long size = slen_max = name_max;
84 if (name_max != size)
85 slen_max = -1;
88 #endif
90 if (HAVE_DOS_FILE_NAMES && slen_max <= 12)
92 /* Live within DOS's 8.3 limit. */
93 char *dot = strchr (s, '.');
94 if (dot)
96 slen -= dot + 1 - s;
97 s = dot + 1;
98 slen_max = 3;
100 else
101 slen_max = 8;
102 extlen = 9; /* Don't use EXT. */
105 if (slen + extlen <= slen_max)
106 strcpy (s + slen, ext);
107 else
109 if (slen_max <= slen)
110 slen = slen_max - 1;
111 s[slen] = e;
112 s[slen + 1] = 0;