• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2021 The Tint Authors.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 //     http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 
15 #include "src/utils/io/tmpfile.h"
16 
17 #include <stdio.h>
18 #include <cstdio>
19 
20 namespace tint {
21 namespace utils {
22 
23 namespace {
24 
TmpFilePath(const std::string & ext)25 std::string TmpFilePath(const std::string& ext) {
26   char name[L_tmpnam];
27   // As we're adding an extension, to ensure the file is really unique, try
28   // creating it, failing if it already exists.
29   while (tmpnam_s(name, L_tmpnam - 1) == 0) {
30     std::string name_with_ext = std::string(name) + ext;
31     FILE* f = nullptr;
32     // The "x" arg forces the function to fail if the file already exists.
33     fopen_s(&f, name_with_ext.c_str(), "wbx");
34     if (f) {
35       fclose(f);
36       return name_with_ext;
37     }
38   }
39   return {};
40 }
41 
42 }  // namespace
43 
TmpFile(std::string ext)44 TmpFile::TmpFile(std::string ext) : path_(TmpFilePath(ext)) {}
45 
~TmpFile()46 TmpFile::~TmpFile() {
47   if (!path_.empty()) {
48     remove(path_.c_str());
49   }
50 }
51 
Append(const void * data,size_t size) const52 bool TmpFile::Append(const void* data, size_t size) const {
53   FILE* file = nullptr;
54   if (fopen_s(&file, path_.c_str(), "ab") != 0) {
55     return false;
56   }
57   fwrite(data, size, 1, file);
58   fclose(file);
59   return true;
60 }
61 
62 }  // namespace utils
63 }  // namespace tint
64