open_for_write_would_lose_data.c 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. /*
  2. * Unix implementation of open_for_write_would_lose_data().
  3. */
  4. #include <sys/types.h>
  5. #include <sys/stat.h>
  6. #include "putty.h"
  7. bool open_for_write_would_lose_data(const Filename *fn)
  8. {
  9. struct stat st;
  10. if (stat(fn->path, &st) < 0) {
  11. /*
  12. * If the file doesn't even exist, we obviously want to return
  13. * false. If we failed to stat it for any other reason,
  14. * ignoring the precise error code and returning false still
  15. * doesn't seem too unreasonable, because then we'll try to
  16. * open the file for writing and report _that_ error, which is
  17. * likely to be more to the point.
  18. */
  19. return false;
  20. }
  21. /*
  22. * OK, something exists at this pathname and we've found out
  23. * something about it. But an open-for-write will only
  24. * destructively truncate it if it's a regular file with nonzero
  25. * size. If it's empty, or some other kind of special thing like a
  26. * character device (e.g. /dev/tty) or a named pipe, then opening
  27. * it for write is already non-destructive and it's pointless and
  28. * annoying to warn about it just because the same file can be
  29. * opened for reading. (Indeed, if it's a named pipe, opening it
  30. * for reading actually _causes inconvenience_ in its own right,
  31. * even before the question of whether it gives misleading
  32. * information.)
  33. */
  34. if (S_ISREG(st.st_mode) && st.st_size > 0) {
  35. return true;
  36. }
  37. return false;
  38. }