dated_copy.cpp 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. // This file is part of libigl, a simple c++ geometry processing library.
  2. //
  3. // Copyright (C) 2014 Alec Jacobson <[email protected]>
  4. //
  5. // This Source Code Form is subject to the terms of the Mozilla Public License
  6. // v. 2.0. If a copy of the MPL was not distributed with this file, You can
  7. // obtain one at http://mozilla.org/MPL/2.0/.
  8. #include "dated_copy.h"
  9. #include "dirname.h"
  10. #include "basename.h"
  11. #include <ctime>
  12. #include <fstream>
  13. #include <sys/types.h>
  14. #include <sys/stat.h>
  15. #include <iostream>
  16. #if !defined(_WIN32)
  17. #include <unistd.h>
  18. IGL_INLINE bool igl::dated_copy(const std::string & src_path, const std::string & dir)
  19. {
  20. // Get time and date as string
  21. char buffer[80];
  22. time_t rawtime;
  23. struct tm * timeinfo;
  24. time (&rawtime);
  25. timeinfo = localtime (&rawtime);
  26. // ISO 8601 format with hyphens instead of colons and no timezone offset
  27. strftime (buffer,80,"%Y-%m-%dT%H-%M-%S",timeinfo);
  28. std::string src_basename = basename(src_path);
  29. std::string dst_basename = src_basename+"-"+buffer;
  30. std::string dst_path = dir+"/"+dst_basename;
  31. std::cerr<<"Saving binary to "<<dst_path;
  32. {
  33. // http://stackoverflow.com/a/10195497/148668
  34. std::ifstream src(src_path,std::ios::binary);
  35. if (!src.is_open())
  36. {
  37. std::cerr<<" failed."<<std::endl;
  38. return false;
  39. }
  40. std::ofstream dst(dst_path,std::ios::binary);
  41. if(!dst.is_open())
  42. {
  43. std::cerr<<" failed."<<std::endl;
  44. return false;
  45. }
  46. dst << src.rdbuf();
  47. }
  48. std::cerr<<" succeeded."<<std::endl;
  49. std::cerr<<"Setting permissions of "<<dst_path;
  50. {
  51. int src_posix = fileno(fopen(src_path.c_str(),"r"));
  52. if(src_posix == -1)
  53. {
  54. std::cerr<<" failed."<<std::endl;
  55. return false;
  56. }
  57. struct stat fst;
  58. fstat(src_posix,&fst);
  59. int dst_posix = fileno(fopen(dst_path.c_str(),"r"));
  60. if(dst_posix == -1)
  61. {
  62. std::cerr<<" failed."<<std::endl;
  63. return false;
  64. }
  65. //update to the same uid/gid
  66. if(fchown(dst_posix,fst.st_uid,fst.st_gid))
  67. {
  68. std::cerr<<" failed."<<std::endl;
  69. return false;
  70. }
  71. //update the permissions
  72. if(fchmod(dst_posix,fst.st_mode) == -1)
  73. {
  74. std::cerr<<" failed."<<std::endl;
  75. return false;
  76. }
  77. std::cerr<<" succeeded."<<std::endl;
  78. }
  79. return true;
  80. }
  81. IGL_INLINE bool igl::dated_copy(const std::string & src_path)
  82. {
  83. return dated_copy(src_path,dirname(src_path));
  84. }
  85. #endif