dated_copy.cpp 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. // This file is part of libigl, a simple c++ geometry processing library.
  2. //
  3. // Copyright (C) 2014 Alec Jacobson <alecjacobson@gmail.com>
  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. using namespace std;
  21. // Get time and date as string
  22. char buffer[80];
  23. time_t rawtime;
  24. struct tm * timeinfo;
  25. time (&rawtime);
  26. timeinfo = localtime (&rawtime);
  27. // ISO 8601 format with hyphens instead of colons and no timezone offset
  28. strftime (buffer,80,"%Y-%m-%dT%H-%M-%S",timeinfo);
  29. string src_basename = basename(src_path);
  30. string dst_basename = src_basename+"-"+buffer;
  31. string dst_path = dir+"/"+dst_basename;
  32. cerr<<"Saving binary to "<<dst_path;
  33. {
  34. // http://stackoverflow.com/a/10195497/148668
  35. ifstream src(src_path,ios::binary);
  36. if (!src.is_open())
  37. {
  38. cerr<<" failed."<<endl;
  39. return false;
  40. }
  41. ofstream dst(dst_path,ios::binary);
  42. if(!dst.is_open())
  43. {
  44. cerr<<" failed."<<endl;
  45. return false;
  46. }
  47. dst << src.rdbuf();
  48. }
  49. cerr<<" succeeded."<<endl;
  50. cerr<<"Setting permissions of "<<dst_path;
  51. {
  52. int src_posix = fileno(fopen(src_path.c_str(),"r"));
  53. if(src_posix == -1)
  54. {
  55. cerr<<" failed."<<endl;
  56. return false;
  57. }
  58. struct stat fst;
  59. fstat(src_posix,&fst);
  60. int dst_posix = fileno(fopen(dst_path.c_str(),"r"));
  61. if(dst_posix == -1)
  62. {
  63. cerr<<" failed."<<endl;
  64. return false;
  65. }
  66. //update to the same uid/gid
  67. if(fchown(dst_posix,fst.st_uid,fst.st_gid))
  68. {
  69. cerr<<" failed."<<endl;
  70. return false;
  71. }
  72. //update the permissions
  73. if(fchmod(dst_posix,fst.st_mode) == -1)
  74. {
  75. cerr<<" failed."<<endl;
  76. return false;
  77. }
  78. cerr<<" succeeded."<<endl;
  79. }
  80. return true;
  81. }
  82. IGL_INLINE bool igl::dated_copy(const std::string & src_path)
  83. {
  84. return dated_copy(src_path,dirname(src_path));
  85. }
  86. #endif