file_util.cc 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. // Copyright (c) 2016 The WebM project authors. All Rights Reserved.
  2. //
  3. // Use of this source code is governed by a BSD-style license
  4. // that can be found in the LICENSE file in the root of the source
  5. // tree. An additional intellectual property rights grant can be found
  6. // in the file PATENTS. All contributing project authors may
  7. // be found in the AUTHORS file in the root of the source tree.
  8. #include "common/file_util.h"
  9. #include <sys/stat.h>
  10. #ifndef _MSC_VER
  11. #include <unistd.h> // close()
  12. #endif
  13. #include <cstdio>
  14. #include <cstdlib>
  15. #include <cstring>
  16. #include <fstream>
  17. #include <ios>
  18. namespace libwebm {
  19. std::string GetTempFileName() {
  20. #if !defined _MSC_VER && !defined __MINGW32__
  21. std::string temp_file_name_template_str =
  22. std::string(std::getenv("TEST_TMPDIR") ? std::getenv("TEST_TMPDIR") :
  23. ".") +
  24. "/libwebm_temp.XXXXXX";
  25. char* temp_file_name_template =
  26. new char[temp_file_name_template_str.length() + 1];
  27. memset(temp_file_name_template, 0, temp_file_name_template_str.length() + 1);
  28. temp_file_name_template_str.copy(temp_file_name_template,
  29. temp_file_name_template_str.length(), 0);
  30. int fd = mkstemp(temp_file_name_template);
  31. std::string temp_file_name =
  32. (fd != -1) ? std::string(temp_file_name_template) : std::string();
  33. delete[] temp_file_name_template;
  34. if (fd != -1) {
  35. close(fd);
  36. }
  37. return temp_file_name;
  38. #else
  39. char tmp_file_name[_MAX_PATH];
  40. errno_t err = tmpnam_s(tmp_file_name);
  41. if (err == 0) {
  42. return std::string(tmp_file_name);
  43. }
  44. return std::string();
  45. #endif
  46. }
  47. uint64_t GetFileSize(const std::string& file_name) {
  48. uint64_t file_size = 0;
  49. #ifndef _MSC_VER
  50. struct stat st;
  51. st.st_size = 0;
  52. if (stat(file_name.c_str(), &st) == 0) {
  53. #else
  54. struct _stat st;
  55. st.st_size = 0;
  56. if (_stat(file_name.c_str(), &st) == 0) {
  57. #endif
  58. file_size = st.st_size;
  59. }
  60. return file_size;
  61. }
  62. TempFileDeleter::TempFileDeleter() { file_name_ = GetTempFileName(); }
  63. TempFileDeleter::~TempFileDeleter() {
  64. std::ifstream file(file_name_.c_str());
  65. if (file.good()) {
  66. file.close();
  67. std::remove(file_name_.c_str());
  68. }
  69. }
  70. } // namespace libwebm