.
[coreutils.git] / lib / addext.c
blob56d0e4f4af6ad0d5fe5dc5b4975ce2f9e25458bc
1 /* addext.c -- add an extension to a file name
2 Copyright (C) 1990, 1997 Free Software Foundation, Inc.
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.
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.
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 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */
19 /* Written by David MacKenzie <djm@gnu.ai.mit.edu> and Paul Eggert */
21 #if HAVE_CONFIG_H
22 # include <config.h>
23 #endif
25 #ifndef HAVE_DOS_FILE_NAMES
26 #define HAVE_DOS_FILE_NAMES 0
27 #endif
28 #ifndef HAVE_LONG_FILE_NAMES
29 #define HAVE_LONG_FILE_NAMES 0
30 #endif
32 #include <backupfile.h>
34 #if HAVE_LIMITS_H
35 # include <limits.h>
36 #endif
37 #ifndef _POSIX_NAME_MAX
38 #define _POSIX_NAME_MAX 14
39 #endif
41 #include <sys/types.h>
42 #if HAVE_STRING_H
43 # include <string.h>
44 #else
45 # include <strings.h>
46 #endif
48 #if HAVE_UNISTD_H
49 # include <unistd.h>
50 #endif
52 /* Append to FILENAME the extension EXT, unless the result would be too long,
53 in which case just append the character E. */
55 void
56 addext (filename, ext, e)
57 char *filename;
58 char const *ext;
59 int e;
61 char *s = base_name (filename);
62 size_t slen = strlen (s), extlen = strlen (ext);
63 long slen_max = -1;
65 #if HAVE_PATHCONF && defined _PC_NAME_MAX
66 if (slen + extlen <= _POSIX_NAME_MAX && ! HAVE_DOS_FILE_NAMES)
67 /* The file name is so short there's no need to call pathconf. */
68 slen_max = _POSIX_NAME_MAX;
69 else if (s == filename)
70 slen_max = pathconf (".", _PC_NAME_MAX);
71 else
73 char c = *s;
74 *s = 0;
75 slen_max = pathconf (filename, _PC_NAME_MAX);
76 *s = c;
78 #endif
79 if (slen_max < 0)
80 slen_max = HAVE_LONG_FILE_NAMES ? 255 : 14;
82 if (HAVE_DOS_FILE_NAMES && slen_max <= 12)
84 /* Live within DOS's 8.3 limit. */
85 char *dot = strchr (s, '.');
86 if (dot)
88 slen -= dot + 1 - s;
89 s = dot + 1;
90 slen_max = 3;
92 else
93 slen_max = 8;
94 extlen = 9; /* Don't use EXT. */
97 if (slen + extlen <= slen_max)
98 strcpy (s + slen, ext);
99 else
101 if (slen_max <= slen)
102 slen = slen_max - 1;
103 s[slen] = e;
104 s[slen + 1] = 0;