rename.c 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. /***************************************************************************
  2. * _ _ ____ _
  3. * Project ___| | | | _ \| |
  4. * / __| | | | |_) | |
  5. * | (__| |_| | _ <| |___
  6. * \___|\___/|_| \_\_____|
  7. *
  8. * Copyright (C) 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
  9. *
  10. * This software is licensed as described in the file COPYING, which
  11. * you should have received as part of this distribution. The terms
  12. * are also available at https://curl.haxx.se/docs/copyright.html.
  13. *
  14. * You may opt to use, copy, modify, merge, publish, distribute and/or sell
  15. * copies of the Software, and permit persons to whom the Software is
  16. * furnished to do so, under the terms of the COPYING file.
  17. *
  18. * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
  19. * KIND, either express or implied.
  20. *
  21. ***************************************************************************/
  22. #include "rename.h"
  23. #include "curl_setup.h"
  24. #if (!defined(CURL_DISABLE_HTTP) && !defined(CURL_DISABLE_COOKIES)) || \
  25. defined(USE_ALTSVC)
  26. #include "timeval.h"
  27. /* The last 3 #include files should be in this order */
  28. #include "curl_printf.h"
  29. #include "curl_memory.h"
  30. #include "memdebug.h"
  31. /* return 0 on success, 1 on error */
  32. int Curl_rename(const char *oldpath, const char *newpath)
  33. {
  34. #ifdef WIN32
  35. /* rename() on Windows doesn't overwrite, so we can't use it here.
  36. MoveFileExA() will overwrite and is usually atomic, however it fails
  37. when there are open handles to the file. */
  38. const int max_wait_ms = 1000;
  39. struct curltime start = Curl_now();
  40. for(;;) {
  41. timediff_t diff;
  42. if(MoveFileExA(oldpath, newpath, MOVEFILE_REPLACE_EXISTING))
  43. break;
  44. diff = Curl_timediff(Curl_now(), start);
  45. if(diff < 0 || diff > max_wait_ms)
  46. return 1;
  47. Sleep(1);
  48. }
  49. #else
  50. if(rename(oldpath, newpath))
  51. return 1;
  52. #endif
  53. return 0;
  54. }
  55. #endif