1 /* Determine whether two file names refer to the same file.
3 Copyright (C) 1997-2000, 2002-2006, 2009-2017 Free Software Foundation, Inc.
5 This program is free software: you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation; either version 3 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with this program. If not, see <https://www.gnu.org/licenses/>. */
18 /* written by Jim Meyering */
26 #include <sys/types.h>
34 #ifndef _POSIX_NAME_MAX
35 # define _POSIX_NAME_MAX 14
41 #include "same-inode.h"
44 # define MIN(a, b) ((a) < (b) ? (a) : (b))
47 /* Return nonzero if SOURCE and DEST point to the same name in the same
51 same_name (const char *source
, const char *dest
)
53 /* Compare the basenames. */
54 char const *source_basename
= last_component (source
);
55 char const *dest_basename
= last_component (dest
);
56 size_t source_baselen
= base_len (source_basename
);
57 size_t dest_baselen
= base_len (dest_basename
);
58 bool identical_basenames
=
59 (source_baselen
== dest_baselen
60 && memcmp (source_basename
, dest_basename
, dest_baselen
) == 0);
61 bool compare_dirs
= identical_basenames
;
64 #if ! _POSIX_NO_TRUNC && HAVE_PATHCONF && defined _PC_NAME_MAX
65 /* This implementation silently truncates components of file names. If
66 the base names might be truncated, check whether the truncated
67 base names are the same, while checking the directories. */
68 size_t slen_max
= HAVE_LONG_FILE_NAMES
? 255 : _POSIX_NAME_MAX
;
69 size_t min_baselen
= MIN (source_baselen
, dest_baselen
);
70 if (slen_max
<= min_baselen
71 && memcmp (source_basename
, dest_basename
, slen_max
) == 0)
77 struct stat source_dir_stats
;
78 struct stat dest_dir_stats
;
79 char *source_dirname
, *dest_dirname
;
81 /* Compare the parent directories (via the device and inode numbers). */
82 source_dirname
= dir_name (source
);
83 dest_dirname
= dir_name (dest
);
85 if (stat (source_dirname
, &source_dir_stats
))
87 /* Shouldn't happen. */
88 error (1, errno
, "%s", source_dirname
);
91 if (stat (dest_dirname
, &dest_dir_stats
))
93 /* Shouldn't happen. */
94 error (1, errno
, "%s", dest_dirname
);
97 same
= SAME_INODE (source_dir_stats
, dest_dir_stats
);
99 #if ! _POSIX_NO_TRUNC && HAVE_PATHCONF && defined _PC_NAME_MAX
100 if (same
&& ! identical_basenames
)
102 long name_max
= (errno
= 0, pathconf (dest_dirname
, _PC_NAME_MAX
));
107 /* Shouldn't happen. */
108 error (1, errno
, "%s", dest_dirname
);
113 same
= (name_max
<= min_baselen
114 && memcmp (source_basename
, dest_basename
, name_max
) == 0);
118 free (source_dirname
);