dated_copy.cpp 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. #include "dated_copy.h"
  2. #include "dirname.h"
  3. #include "basename.h"
  4. #include <ctime>
  5. #include <fstream>
  6. #include <sys/types.h>
  7. #include <sys/stat.h>
  8. #include <unistd.h>
  9. #include <iostream>
  10. IGL_INLINE bool igl::dated_copy(const std::string & src_path, const std::string & dir)
  11. {
  12. using namespace std;
  13. using namespace igl;
  14. // Get time and date as string
  15. char buffer[80];
  16. time_t rawtime;
  17. struct tm * timeinfo;
  18. time (&rawtime);
  19. timeinfo = localtime (&rawtime);
  20. // ISO 8601 format with hyphens instead of colons and no timezone offset
  21. strftime (buffer,80,"%Y-%m-%dT%H-%M-%S",timeinfo);
  22. string src_basename = basename(src_path);
  23. string dst_basename = src_basename+"-"+buffer;
  24. string dst_path = dir+"/"+dst_basename;
  25. cerr<<"Saving binary to "<<dst_path;
  26. {
  27. // http://stackoverflow.com/a/10195497/148668
  28. ifstream src(src_path,ios::binary);
  29. if (!src.is_open())
  30. {
  31. cerr<<" failed."<<endl;
  32. return false;
  33. }
  34. ofstream dst(dst_path,ios::binary);
  35. if(!dst.is_open())
  36. {
  37. cerr<<" failed."<<endl;
  38. return false;
  39. }
  40. dst << src.rdbuf();
  41. }
  42. cerr<<" succeeded."<<endl;
  43. cerr<<"Setting permissions of "<<dst_path;
  44. {
  45. int src_posix = fileno(fopen(src_path.c_str(),"r"));
  46. if(src_posix == -1)
  47. {
  48. cerr<<" failed."<<endl;
  49. return false;
  50. }
  51. struct stat fst;
  52. fstat(src_posix,&fst);
  53. int dst_posix = fileno(fopen(dst_path.c_str(),"r"));
  54. if(dst_posix == -1)
  55. {
  56. cerr<<" failed."<<endl;
  57. return false;
  58. }
  59. //update to the same uid/gid
  60. if(fchown(dst_posix,fst.st_uid,fst.st_gid))
  61. {
  62. cerr<<" failed."<<endl;
  63. return false;
  64. }
  65. //update the permissions
  66. if(fchmod(dst_posix,fst.st_mode) == -1)
  67. {
  68. cerr<<" failed."<<endl;
  69. return false;
  70. }
  71. cerr<<" succeeded."<<endl;
  72. }
  73. return true;
  74. }
  75. IGL_INLINE bool igl::dated_copy(const std::string & src_path)
  76. {
  77. return dated_copy(src_path,dirname(src_path));
  78. }