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 10 #include <sys/stat.h> 11 #ifndef _MSC_VER 12 #include <unistd.h> // close() 13 #endif 14 15 #include <cstdio> 16 #include <cstdlib> 17 #include <cstring> 18 #include <fstream> 19 #include <ios> 20 21 namespace libwebm { 22 GetTempFileName()23std::string GetTempFileName() { 24 #if !defined _MSC_VER && !defined __MINGW32__ 25 std::string temp_file_name_template_str = 26 std::string(std::getenv("TEST_TMPDIR") ? std::getenv("TEST_TMPDIR") : 27 ".") + 28 "/libwebm_temp.XXXXXX"; 29 char* temp_file_name_template = 30 new char[temp_file_name_template_str.length() + 1]; 31 memset(temp_file_name_template, 0, temp_file_name_template_str.length() + 1); 32 temp_file_name_template_str.copy(temp_file_name_template, 33 temp_file_name_template_str.length(), 0); 34 int fd = mkstemp(temp_file_name_template); 35 std::string temp_file_name = 36 (fd != -1) ? std::string(temp_file_name_template) : std::string(); 37 delete[] temp_file_name_template; 38 if (fd != -1) { 39 close(fd); 40 } 41 return temp_file_name; 42 #else 43 char tmp_file_name[_MAX_PATH]; 44 errno_t err = tmpnam_s(tmp_file_name); 45 if (err == 0) { 46 return std::string(tmp_file_name); 47 } 48 return std::string(); 49 #endif 50 } 51 GetFileSize(const std::string & file_name)52uint64_t GetFileSize(const std::string& file_name) { 53 uint64_t file_size = 0; 54 #ifndef _MSC_VER 55 struct stat st; 56 st.st_size = 0; 57 if (stat(file_name.c_str(), &st) == 0) { 58 #else 59 struct _stat st; 60 st.st_size = 0; 61 if (_stat(file_name.c_str(), &st) == 0) { 62 #endif 63 file_size = st.st_size; 64 } 65 return file_size; 66 } 67 68 TempFileDeleter::TempFileDeleter() { file_name_ = GetTempFileName(); } 69 70 TempFileDeleter::~TempFileDeleter() { 71 std::ifstream file(file_name_.c_str()); 72 if (file.good()) { 73 file.close(); 74 std::remove(file_name_.c_str()); 75 } 76 } 77 78 } // namespace libwebm 79