dated_copy.cpp 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  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 <unistd.h>
  16. #include <iostream>
  17. IGL_INLINE bool igl::dated_copy(const std::string & src_path, const std::string & dir)
  18. {
  19. using namespace std;
  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. string src_basename = basename(src_path);
  29. string dst_basename = src_basename+"-"+buffer;
  30. string dst_path = dir+"/"+dst_basename;
  31. cerr<<"Saving binary to "<<dst_path;
  32. {
  33. // http://stackoverflow.com/a/10195497/148668
  34. ifstream src(src_path,ios::binary);
  35. if (!src.is_open())
  36. {
  37. cerr<<" failed."<<endl;
  38. return false;
  39. }
  40. ofstream dst(dst_path,ios::binary);
  41. if(!dst.is_open())
  42. {
  43. cerr<<" failed."<<endl;
  44. return false;
  45. }
  46. dst << src.rdbuf();
  47. }
  48. cerr<<" succeeded."<<endl;
  49. 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. cerr<<" failed."<<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. cerr<<" failed."<<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. cerr<<" failed."<<endl;
  69. return false;
  70. }
  71. //update the permissions
  72. if(fchmod(dst_posix,fst.st_mode) == -1)
  73. {
  74. cerr<<" failed."<<endl;
  75. return false;
  76. }
  77. cerr<<" succeeded."<<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. }