Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Safely create temporary files and directories #3378

Merged
merged 2 commits into from
Nov 28, 2015
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 31 additions & 13 deletions include/caffe/util/io.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -2,33 +2,51 @@
#define CAFFE_UTIL_IO_H_

#include <boost/filesystem.hpp>
#include <iomanip>
#include <iostream> // NOLINT(readability/streams)
#include <string>

#include "google/protobuf/message.h"

#include "caffe/common.hpp"
#include "caffe/proto/caffe.pb.h"
#include "caffe/util/format.hpp"

#ifndef CAFFE_TMP_DIR_RETRIES
#define CAFFE_TMP_DIR_RETRIES 100
#endif

namespace caffe {

using ::google::protobuf::Message;
using ::boost::filesystem::path;

inline void MakeTempFilename(string* temp_filename) {
temp_filename->clear();
const path& model = boost::filesystem::temp_directory_path()
/"caffe_test.%%%%%%";
*temp_filename = boost::filesystem::unique_path(model).string();
}

inline void MakeTempDir(string* temp_dirname) {
temp_dirname->clear();
const path& model = boost::filesystem::temp_directory_path()
/"caffe_test.%%%%%%";
const path& dir = boost::filesystem::unique_path(model).string();
bool directoryCreated = boost::filesystem::create_directory(dir);
CHECK(directoryCreated);
*temp_dirname = dir.string();
const path& model =
boost::filesystem::temp_directory_path()/"caffe_test.%%%%-%%%%";
for ( int i = 0; i < CAFFE_TMP_DIR_RETRIES; i++ ) {
const path& dir = boost::filesystem::unique_path(model).string();
bool done = boost::filesystem::create_directory(dir);
if ( done ) {
*temp_dirname = dir.string();
return;
}
}
LOG(FATAL) << "Failed to create a temporary directory.";
}

inline void MakeTempFilename(string* temp_filename) {
static path temp_files_subpath;
static uint64_t next_temp_file = 0;
temp_filename->clear();
if ( temp_files_subpath.empty() ) {
string path_string="";
MakeTempDir(&path_string);
temp_files_subpath = path_string;
}
*temp_filename =
(temp_files_subpath/caffe::format_int(next_temp_file++, 9)).string();
}

bool ReadProtoFromTextFile(const char* filename, Message* proto);
Expand Down