move_file_replace_if_exists.cpp 858 B

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