move_file_if_exists.cpp 934 B

12345678910111213141516171819202122232425262728293031323334
  1. //
  2. // $Id$
  3. //
  4. #include<__vic/fs.h>
  5. #include<__vic/posix/error.h>
  6. #include<__vic/throw_errno.h>
  7. #include<unistd.h>
  8. #include<cerrno>
  9. namespace __vic {
  10. //----------------------------------------------------------------------------
  11. bool move_file_if_exists(const char *src_path, const char *dest_path)
  12. {
  13. // std::rename overwrites existing entry so we don't use it
  14. if(::link(src_path, dest_path))
  15. switch(int err = errno)
  16. {
  17. __VIC_CASE_ENOENT // input file doesn't exist
  18. return false;
  19. case EXDEV: // src and dest are not on the same filesystem
  20. if(!copy_file_if_exists(src_path, dest_path)) return false;
  21. break;
  22. default:
  23. throw_errno("link", err);;
  24. }
  25. remove_file_if_exists(src_path);
  26. return true; // OK
  27. }
  28. //----------------------------------------------------------------------------
  29. } // namespace