3 * Copyright 2015 gRPC authors.
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
9 * http://www.apache.org/licenses/LICENSE-2.0
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.
19 #include <grpc/support/port_platform.h>
21 #ifdef GPR_POSIX_TMPFILE
23 #include "src/core/lib/gpr/tmpfile.h"
30 #include <grpc/support/alloc.h>
31 #include <grpc/support/log.h>
32 #include <grpc/support/string_util.h>
34 #include "src/core/lib/gpr/string.h"
36 FILE* gpr_tmpfile(const char* prefix, char** tmp_filename) {
37 FILE* result = nullptr;
38 char* filename_template;
41 if (tmp_filename != nullptr) *tmp_filename = nullptr;
43 gpr_asprintf(&filename_template, "/tmp/%s_XXXXXX", prefix);
44 GPR_ASSERT(filename_template != nullptr);
46 fd = mkstemp(filename_template);
48 gpr_log(GPR_ERROR, "mkstemp failed for filename_template %s with error %s.",
49 filename_template, strerror(errno));
52 result = fdopen(fd, "w+");
53 if (result == nullptr) {
54 gpr_log(GPR_ERROR, "Could not open file %s from fd %d (error = %s).",
55 filename_template, fd, strerror(errno));
56 unlink(filename_template);
62 if (result != nullptr && tmp_filename != nullptr) {
63 *tmp_filename = filename_template;
65 gpr_free(filename_template);
70 #endif /* GPR_POSIX_TMPFILE */