rename.c 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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.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(CURL_DISABLE_ALTSVC)
  26. #include "curl_multibyte.h"
  27. #include "timeval.h"
  28. /* The last 3 #include files should be in this order */
  29. #include "curl_printf.h"
  30. #include "curl_memory.h"
  31. #include "memdebug.h"
  32. /* return 0 on success, 1 on error */
  33. int Curl_rename(const char *oldpath, const char *newpath)
  34. {
  35. #ifdef WIN32
  36. /* rename() on Windows doesn't overwrite, so we can't use it here.
  37. MoveFileEx() will overwrite and is usually atomic, however it fails
  38. when there are open handles to the file. */
  39. const int max_wait_ms = 1000;
  40. struct curltime start = Curl_now();
  41. TCHAR *tchar_oldpath = curlx_convert_UTF8_to_tchar((char *)oldpath);
  42. TCHAR *tchar_newpath = curlx_convert_UTF8_to_tchar((char *)newpath);
  43. for(;;) {
  44. timediff_t diff;
  45. if(MoveFileEx(tchar_oldpath, tchar_newpath, MOVEFILE_REPLACE_EXISTING)) {
  46. curlx_unicodefree(tchar_oldpath);
  47. curlx_unicodefree(tchar_newpath);
  48. break;
  49. }
  50. diff = Curl_timediff(Curl_now(), start);
  51. if(diff < 0 || diff > max_wait_ms) {
  52. curlx_unicodefree(tchar_oldpath);
  53. curlx_unicodefree(tchar_newpath);
  54. return 1;
  55. }
  56. Sleep(1);
  57. }
  58. #else
  59. if(rename(oldpath, newpath))
  60. return 1;
  61. #endif
  62. return 0;
  63. }
  64. #endif