unlink-if-ordinary.c 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. /* unlink-if-ordinary.c - remove link to a file unless it is special
  2. Copyright (C) 2004-2022 Free Software Foundation, Inc.
  3. This file is part of the libiberty library. This library is free
  4. software; you can redistribute it and/or modify it under the
  5. terms of the GNU General Public License as published by the
  6. Free Software Foundation; either version 2, or (at your option)
  7. any later version.
  8. This library is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with GNU CC; see the file COPYING. If not, write to
  14. the Free Software Foundation, 51 Franklin Street - Fifth Floor, Boston, MA 02110-1301, USA.
  15. As a special exception, if you link this library with files
  16. compiled with a GNU compiler to produce an executable, this does not cause
  17. the resulting executable to be covered by the GNU General Public License.
  18. This exception does not however invalidate any other reasons why
  19. the executable file might be covered by the GNU General Public License. */
  20. /*
  21. @deftypefn Supplemental int unlink_if_ordinary (const char*)
  22. Unlinks the named file, unless it is special (e.g. a device file).
  23. Returns 0 when the file was unlinked, a negative value (and errno set) when
  24. there was an error deleting the file, and a positive value if no attempt
  25. was made to unlink the file because it is special.
  26. @end deftypefn
  27. */
  28. #ifdef HAVE_CONFIG_H
  29. #include "config.h"
  30. #endif
  31. #include <sys/types.h>
  32. #ifdef HAVE_UNISTD_H
  33. #include <unistd.h>
  34. #endif
  35. #if HAVE_SYS_STAT_H
  36. #include <sys/stat.h>
  37. #endif
  38. #include "libiberty.h"
  39. #ifndef S_ISLNK
  40. #ifdef S_IFLNK
  41. #define S_ISLNK(m) (((m) & S_IFMT) == S_IFLNK)
  42. #else
  43. #define S_ISLNK(m) 0
  44. #define lstat stat
  45. #endif
  46. #endif
  47. int
  48. unlink_if_ordinary (const char *name)
  49. {
  50. struct stat st;
  51. if (lstat (name, &st) == 0
  52. && (S_ISREG (st.st_mode) || S_ISLNK (st.st_mode)))
  53. return unlink (name);
  54. return 1;
  55. }