rename.c 2.3 KB

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