CUBRID Engine  latest
filesys_temp.cpp
Go to the documentation of this file.
1 /*
2  * Copyright 2008 Search Solution Corporation
3  * Copyright 2016 CUBRID Corporation
4  *
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  * http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  *
17  */
18 
19 /*
20  * file_sys.cpp: File System namespace & functionality
21  */
22 #include "filesys_temp.hpp"
23 #include <filesystem>
24 #include <stdlib.h>
25 
26 #ifdef LINUX
27 #include "porting.h"
28 #elif WINDOWS
29 #include <cstdio>
30 #include <fcntl.h>
31 #include <io.h>
32 #endif
33 
34 namespace
35 {
36  std::string unique_tmp_filename (const char *prefix="cub_") //generates an unique filename in tmp folder
37  {
38 #ifdef LINUX
39  std::string filename = std::filesystem::temp_directory_path ();
40  filename += "/";
41  filename += prefix;
42  filename += "XXXXXX"; //used with mkstemp()
43  //TBD (not necessary yet)
44 #elif WINDOWS
45  char buf[L_tmpnam] = {};
46  std::string filename = std::tmpnam (buf);
47  auto pos = filename.rfind ('\\');
48  filename.insert (pos+1, prefix);
49 #endif
50  return filename;
51  }
52 }
53 
54 //--------------------------------------------------------------------------------
55 std::pair<std::string, int> filesys::open_temp_filedes (const char *prefix, int flags)
56 {
57 #ifdef LINUX
58  char filename[PATH_MAX] = {};
59  snprintf (filename, sizeof (filename), "%s", unique_tmp_filename (prefix).c_str());
60  auto filedesc = mkostemp (filename, flags);
61 #elif WINDOWS
62  auto filename = unique_tmp_filename (prefix);
63  auto filedesc = _open (filename.c_str(), _O_CREAT|_O_EXCL|_O_RDWR|flags);
64 #endif
65  return {filename, filedesc};
66 }
67 
68 //--------------------------------------------------------------------------------
69 std::pair<std::string, FILE *> filesys::open_temp_file (const char *prefix, const char *mode, int flags)
70 {
71 #ifdef LINUX
72  char filename[PATH_MAX] = {};
73  snprintf (filename, sizeof (filename), "%s", unique_tmp_filename (prefix).c_str());
74  auto filedesc = mkostemp (filename, flags);
75  FILE *fileptr = fdopen (filedesc, mode);
76 #elif WINDOWS
77  auto filename = unique_tmp_filename (prefix);
78  auto *fileptr = fopen (filename.c_str(), mode);
79 #endif
80  return {filename, fileptr};
81 }
static enum scanner_mode mode
std::pair< std::string, FILE * > open_temp_file(const char *prefix, const char *mode="w", int flags=0)
std::pair< std::string, int > open_temp_filedes(const char *prefix, int flags=0)