inline void copy_files(const boost::filesystem::path& path_from, const boost::filesystem::path& path_to) { if (path_from.empty() || path_to.empty()) throw std::runtime_error("empty path"); if (! boost::filesystem::exists(path_from) || ! boost::filesystem::exists(path_to)) throw std::runtime_error("no path"); if (! boost::filesystem::is_directory(path_to)) throw std::runtime_error("destination is not a directory"); boost::filesystem::path destination = path_to / path_from.leaf(); if (! boost::filesystem::is_directory(path_from)) boost::filesystem::copy_file(path_from, destination); else { boost::filesystem::create_directory(destination); boost::filesystem::directory_iterator iter_end; for (boost::filesystem::directory_iterator iter(path_from); iter != iter_end; ++ iter) copy_files(*iter, destination); } }
inline void remove_all(const boost::filesystem::path& path) { if (__is_directory(path)) { std::vector<boost::filesystem::path> paths; #if BOOST_FILESYSTEM_VERSION == 2 DIR* dirp = (path.empty() ? ::opendir(".") : ::opendir(path.directory_string().c_str())); #else DIR* dirp = (path.empty() ? ::opendir(".") : ::opendir(path.string().c_str())); #endif if (dirp) { struct dirent* dp; do { errno = 0; if ((dp = readdir(dirp)) != 0) { const std::string path_leaf(dp->d_name); if (path_leaf != "." && path_leaf != "..") paths.push_back(path / path_leaf); } } while (dp); ::closedir(dirp); } std::for_each(paths.begin(), paths.end(), utils::filesystem::remove_all); } #if BOOST_FILESYSTEM_VERSION == 2 if (__exists(path)) ::remove(path.file_string().c_str()); #else if (__exists(path)) ::remove(path.string().c_str()); #endif errno = 0; }
static void setupLogging(std::string levelArg, bfs::path pathArg) { bp::log::Configurator cfg; cfg.loadConfigFile(); // Set the default log file. // One case we'll need this is when daemon is in -fg mode but // configured logging destination is "file". cfg.setPath(bp::paths::getObfuscatedWritableDirectory() / "BrowserPlusCore.log"); // Currently there is no policy for service harness processes to // log to any other file than BrowserPlusCore.log. // Let's take the tack for now that harnesses never rollover that file. cfg.setFileMode( bp::log::kAppend ); //// // Handle any command line arguments. // if (!levelArg.empty()) { cfg.setLevel( bp::log::levelFromString( levelArg ) ); } if (!pathArg.empty()) { cfg.setDestination( bp::log::kDestFile ); cfg.setPath( pathArg ); } // Configure. cfg.configure(); }
void logger_init( const std::string& path, LogPriority level, const std::string& format, const std::string& compress, const std::string& purgeCount) { if (_enableLogging) { _logFile = path; if (!_logDirectory.empty()) { // // Application override for the directory // std::string lfile = OSS::boost_file_name(_logFile); _logFile = operator/(_logDirectory, lfile); } AutoPtr<FileChannel> rotatedFileChannel(new FileChannel(OSS::boost_path(_logFile))); rotatedFileChannel->setProperty("rotation", "daily"); rotatedFileChannel->setProperty("archive", "timestamp"); rotatedFileChannel->setProperty("compress", compress); rotatedFileChannel->setProperty("purgeCount", purgeCount); AutoPtr<Formatter> formatter(new PatternFormatter(format.c_str())); AutoPtr<Channel> formattingChannel(new FormattingChannel(formatter, rotatedFileChannel)); _pLogger = &(Logger::create("OSS.logger", formattingChannel, level)); } }
void cFlyon::Set_Image_Dir(fs::path dir) { if (dir.empty()) { return; } // if not image directory if (!File_Exists(pResource_Manager->Get_Game_Pixmaps_Directory() / dir / utf8_to_path("closed_1.settings")) && !File_Exists(pResource_Manager->Get_Game_Pixmaps_Directory() / dir / utf8_to_path("closed_1.png"))) { std::cerr << "Warning: Flyon image files not found; does the flyon directory " << path_to_utf8(dir) << " exist?" << std::endl; return; } m_img_dir = dir; // clear images Clear_Images(); // set images Add_Image(pVideo->Get_Surface(m_img_dir / utf8_to_path("closed_1.png"))); Add_Image(pVideo->Get_Surface(m_img_dir / utf8_to_path("closed_2.png"))); Add_Image(pVideo->Get_Surface(m_img_dir / utf8_to_path("open_1.png"))); Add_Image(pVideo->Get_Surface(m_img_dir / utf8_to_path("open_2.png"))); // set start image Set_Image_Num(0, 1); Set_Animation(1); Set_Animation_Image_Range(0, 3); Set_Time_All(130, 1); Reset_Animation(); }
bool statFile(const bfs::path& p, FileInfo& fi) { // init to zero memset(&fi, 0, sizeof(fi)); if (p.empty()) return false; struct stat s; if (::stat(p.c_str(), &s) != 0) return false; // set times #ifdef MACOSX fi.mtime = s.st_mtimespec.tv_sec; fi.ctime = s.st_ctimespec.tv_sec; fi.atime = s.st_atimespec.tv_sec; #elif defined(LINUX) fi.mtime = s.st_mtime; fi.ctime = s.st_ctime; fi.atime = s.st_atime; #else #error "unsupported platform" #endif // set mode and size fi.mode = s.st_mode; fi.sizeInBytes = s.st_size; // set device and file ids fi.deviceId = s.st_rdev; fi.fileIdLow = s.st_ino; return true; }
void DataTableWriter::initialise() { using ::std::ios_base; myLastWriteCoords = DataTable::Coords(0, 0); myFullWriteRequired = true; const bool fileExists = fs::exists(myOutputPath); // Make sure that all the folders up the filename exist if(!fileExists) { const fs::path parentPath = myOutputPath.parent_path(); if(!parentPath.empty() && !exists(parentPath)) fs::create_directories(parentPath); } ::std::ios_base::openmode openMode = ios_base::out; if(fileExists && myAppend) openMode = openMode | ios_base::ate; // Try opening the file myOutStream.open(myOutputPath, openMode); // Save the write marker myWriteMarker = myOutStream.tellp(); // Listen for changes to the table myTable.addDataTableChangeListener(this); }
static void _createDirectories(Transport::Config *config, boost::filesystem::path ph) { if (ph.empty() || exists(ph)) { return; } // First create branch, by calling ourself recursively _createDirectories(config, ph.branch_path()); // Now that parent's path exists, create the directory boost::filesystem::create_directory(ph); #ifndef WIN32 if (!CONFIG_STRING(config, "service.group").empty() && !CONFIG_STRING(config, "service.user").empty()) { struct group *gr; if ((gr = getgrnam(CONFIG_STRING(config, "service.group").c_str())) == NULL) { std::cerr << "Invalid service.group name " << CONFIG_STRING(config, "service.group") << "\n"; } struct passwd *pw; if ((pw = getpwnam(CONFIG_STRING(config, "service.user").c_str())) == NULL) { std::cerr << "Invalid service.user name " << CONFIG_STRING(config, "service.user") << "\n"; } chown(ph.string().c_str(), pw->pw_uid, gr->gr_gid); } #endif }
void create_parents( const fs::path &dpath ) { string err( "create_parent(): " ); fs::path branch( dpath.branch_path() ); string who("create_parents"); if( dpath.empty() ) { err.append( "cannot create an empty path." ); throw CannotCreateParents( err ); } else if( !exists(dpath) ) { if( branch.empty() ) create_directory( dpath ); else if( !exists(branch) ) { create_parents( branch ); create_directory( dpath ); } else if( is_directory(branch) ) create_directory( dpath ); else { err.append( branch.native_file_string() ); err.append( " is not a directory." ); throw CannotCreateParents( err ); } } else if( !is_directory(dpath) ) { err.append( dpath.native_file_string() ); err.append( " is not a directory." ); throw CannotCreateParents( err ); } return; }
bool IsPluginMaster(boost::filesystem::path filename) { char buffer[MAXLENGTH]; char* bufptr = buffer; ModHeader modHeader; if (filename.empty()) return false; ifstream file(filename.native().c_str(), ios_base::binary | ios_base::in); if (file.bad()) //throw boss_error(BOSS_ERROR_FILE_READ_FAIL, filename.string()); return false; // Reads the first MAXLENGTH bytes into the buffer file.read(&buffer[0], sizeof(buffer)); // Check for the 'magic' marker at start if (Read<uint>(bufptr) != Record::TES4){ return false; } // Next field is the total header size /*uint headerSize =*/ Read<uint>(bufptr); // Next comes the header record Flags uint flags = Read<uint>(bufptr); // LSb of this record's flags is used to indicate if the // mod is a master or a plugin return ((flags & 0x1) != 0); }
void parse_lang_code_file() { if(g_executable_path.empty()) throw(std::runtime_error("executable_path is empty")); boost::filesystem::path iso_file(g_executable_path/PLUGINS_NAVTEQ_ISO_639_2_UTF_8_TXT); std::ifstream file(iso_file.string()); assert(file.is_open()); std::string line; std::string delim = "|"; if (file.is_open()){ while (getline(file, line, '\n')){ std::vector<std::string> lv; auto start = 0u; auto end = line.find(delim); while (end != std::string::npos){ lv.push_back(line.substr(start, end-start)); start = end + delim.length(); end = line.find(delim, start); } std::string iso_639_2 = lv.at(0); std::string iso_639_1 = lv.at(2); if (!iso_639_1.empty()) g_lang_code_map.insert(std::make_pair(iso_639_2, iso_639_1)); } file.close(); } }
GTEST_TEST_F(ReadFile, write) { ASSERT_FALSE(kFilePath.empty()); static const byte data[5] = { 0x12, 0x34, 0x56, 0x78, 0x90 }; // Create the input file boost::filesystem::ofstream testFile(kFilePath, std::ofstream::binary); testFile.write(reinterpret_cast<const char *>(data), ARRAYSIZE(data)); testFile.flush(); ASSERT_FALSE(testFile.fail()); testFile.close(); // Read the file with our ReadFile class Common::ReadFile file(kFilePath.generic_string()); ASSERT_TRUE(file.isOpen()); EXPECT_EQ(file.size(), ARRAYSIZE(data)); byte readData[ARRAYSIZE(data)]; const size_t readCount = file.read(readData, sizeof(readData)); EXPECT_EQ(readCount, ARRAYSIZE(readData)); file.close(); ASSERT_FALSE(file.isOpen()); // Compare for (size_t i = 0; i < ARRAYSIZE(data); i++) EXPECT_EQ(readData[i], data[i]) << "At index " << i; }
bool DatabaseImpl::exists(const boost::filesystem::path& database) { RAISE_INVALID_ARGUMENT_IF(database.empty(), "database name is empty"); RAISE_INVALID_ARGUMENT_IF(openDatabase_, "database is open"); ManagedDatabaseFiles databaseFiles(database); return databaseFilesExist(databaseFiles); }
void DatabaseImpl::open(const boost::filesystem::path& database, const Options& options) { RAISE_INVALID_ARGUMENT_IF(database.empty(), "database name is empty"); options.validate(); RAISE_INVALID_ARGUMENT_IF(openDatabase_, "database is already open"); openDatabase_.reset(new OpenDatabase(database, options)); }
bool BootstrapFile::open_writer(const boost::filesystem::path& file_path) { const boost::filesystem::path dir_path = file_path.parent_path(); if (!dir_path.empty()) { if (boost::filesystem::exists(dir_path)) { if (!boost::filesystem::is_directory(dir_path)) { LOG_PRINT_RED_L0("export directory path is a file: " << dir_path); return false; } } else { if (!boost::filesystem::create_directory(dir_path)) { LOG_PRINT_RED_L0("Failed to create directory " << dir_path); return false; } } } m_raw_data_file = new std::ofstream(); bool do_initialize_file = false; uint64_t num_blocks = 0; if (! boost::filesystem::exists(file_path)) { LOG_PRINT_L0("creating file"); do_initialize_file = true; num_blocks = 0; } else { num_blocks = count_blocks(file_path.string()); LOG_PRINT_L0("appending to existing file with height: " << num_blocks-1 << " total blocks: " << num_blocks); } m_height = num_blocks; if (do_initialize_file) m_raw_data_file->open(file_path.string(), std::ios_base::binary | std::ios_base::out | std::ios::trunc); else m_raw_data_file->open(file_path.string(), std::ios_base::binary | std::ios_base::out | std::ios::app | std::ios::ate); if (m_raw_data_file->fail()) return false; m_output_stream = new boost::iostreams::stream<boost::iostreams::back_insert_device<buffer_type>>(m_buffer); if (m_output_stream == nullptr) return false; if (do_initialize_file) initialize_file(); return true; }
void writeNotice( const ctLAdder::Format &format, const clMisc::StringVec &lines, const bfs::path &pPath, const std::string &program) { auto year = bp::second_clock::local_time().date().year(); std::cout << format.start << " 2005-" << year << " "; bool first = true; for (const auto &line : lines) { if (first) first = false; else std::cout << "\n" << format.lineStart; std::cout << line; } if (!pPath.empty()) { if (!bfs::is_regular_file(pPath)) { BOOST_THROW_EXCEPTION(clMisc::InvalidPath() << clMisc::ExceptionInfo::FilePath(pPath)); } std::cout << "\n" << format.emptyLineStart << "\n" << format.lineStart << "This file is part of '" << program << "'.\n" << format.emptyLineStart; std::ifstream pFile; pFile.exceptions(std::ios::badbit); pFile.open(pPath.string().c_str()); char buff[1024]; while (pFile.good()) { pFile.getline(buff, sizeof(buff)); buff[pFile.gcount()] = 0; if (!pFile.gcount() && !pFile.good()) break; auto line = std::string(buff); auto qProg = "'" + program + "'"; boost::replace_first(line, "This program", qProg); boost::replace_first(line, "this program", qProg); std::cout << "\n" << (line.empty() ? format.emptyLineStart : format.lineStart) << line; } } std::cout << format.end; }
int main(int argc, char* argv[]) { // the old random dance. std::srand( std::time(NULL) ); // struct sigaction action = {0}; // action.sa_handler = terminated; // sigaction(SIGTERM, &action, NULL); // Set up command line arg parser. option::Stats stats(usage, argc, argv); // The sizes are just suitable maximums. // Trying to declare them on the heap using the sizes from the example crashes. // The example code tries to use the options_max and buffer_max values to initialize // stack arrays. This is illegal as the size isn't known at compile time. Not sure // why it would be included as a sample as it clearly doesn't build. option::Option options[256]; option::Option buffer[256]; // Create the parser in GNU mode (true as first argument). option::Parser parser(true, usage, argc, argv, options, buffer); if ( parser.error() ) return 1; if ( options[CLEAR] ) { vm.clear(); } if ( !indexFilePath.empty() && !process_index_file(indexFilePath, vm) ) { std::cout << "process_index_file failed. Aborting.\n"; return 2; } if ( options[XVAL] ) { vm.crossValidate(xval_k); vm.graciaCrossValidate(xval_k); } if ( options[TRAIN] ) { vm.train(); } if ( options[ERROR] || options[TRAIN] ) { // vm.computeError(ViolenceModel::TRAINING); // vm.computeError(ViolenceModel::X_VALIDATION); // vm.computeError(ViolenceModel::TESTING); } if ( options[PREDICT] ) { std::string predictArg = options[PREDICT].arg; vm.predict(predictArg, 2); } return 0; }
fs::path findParentDir (const fs::path& current, const std::string& name) { if (current.empty()) { return fs::path(); } else if (current.filename() == name) { return current; } else { return findParentDir(current.parent_path(), name); } }
fs::path getLocalStatePath(const fs::path &subpath) { if(!directories_inited) { initDirectorys(); } fs::path res(localstate_dir); if(!subpath.empty()) { res /= subpath; } return res; }
fs::path getConfigPath(const fs::path &subpath) { if(!directories_inited) { initDirectorys(); } fs::path res(config_dir); if(!subpath.empty()) { res /= subpath; } return res; }
fs::path correctPathCase(fs::path Path) { using namespace boost::filesystem; #ifndef CASE_SENSITIVE_FILESYSTEM if (!exists(Path)) return path(); return Path; #else // If the path is OK as it stands, do nothing. if (exists(Path)) return Path; // If the path doesn't seem to be OK, track backwards through it // looking for the point at which the problem first arises. Path // will contain the parts of the path that exist on the current // filesystem, and pathElts will contain the parts after that point, // which may have incorrect case. stack<string> pathElts; while (!Path.empty() && !exists(Path)) { pathElts.push(Path.filename().string()); Path = Path.branch_path(); } // Now proceed forwards through the possibly-incorrect elements. while (!pathElts.empty()) { // Does this element need to be a directory? // (If we are searching for /foo/bar/baz, and /foo contains a file // bar and a directory Bar, then we need to know which is the one // we're looking for. This will still be unreliable if /foo // contains directories bar and Bar, but a full backtracking // search would be complicated; for now this should be adequate!) const bool needDir = pathElts.size() > 1; string elt(pathElts.top()); pathElts.pop(); // Does this element exist? if (exists(Path/elt) && (!needDir || is_directory(Path/elt))) { // If so, use it. Path /= elt; } else { // If not, search for a suitable candidate. to_upper(elt); directory_iterator end; bool found = false; for (directory_iterator dir(Path); dir != end; ++dir) { string uleaf = dir->path().filename().string(); to_upper(uleaf); if (uleaf == elt && (!needDir || is_directory(*dir))) { Path /= dir->path().filename(); found = true; break; } } if (!found) return ""; } } return Path.string(); #endif }
void curl::set_ca_info(const boost::filesystem::path& ca_info) { if (ca_info.empty()) { set_option(CURLOPT_CAINFO, static_cast<const void*>(NULL)); } else { set_option(CURLOPT_CAINFO, static_cast<const void*>(ca_info.string().c_str())); } }
bool getROSPackagePath(const std::string pkgName, boost::filesystem::path & pkgPath) { pkgPath = ros::package::getPath(pkgName); if (pkgPath.empty()) { printf("Could not find package '%s' ", pkgName.c_str()); return false; } else { printf("%s package found here: %s", pkgName.c_str(), pkgPath.c_str()); return true; } }
std::unique_ptr<CPsfStreamProvider> CreatePsfStreamProvider(const boost::filesystem::path& archivePath) { if(archivePath.empty()) { return std::unique_ptr<CPsfStreamProvider>(new CPhysicalPsfStreamProvider()); } else { return std::unique_ptr<CPsfStreamProvider>(new CArchivePsfStreamProvider(archivePath)); } }
Status pathExists(const fs::path& path) { boost::system::error_code ec; if (path.empty()) { return Status(1, "-1"); } // A tri-state determination of presence if (!fs::exists(path, ec) || ec.value() != errc::success) { return Status(1, ec.message()); } return Status(0, "1"); }
inline SAGA_EXPORT std::string leaf(boost::filesystem::path const& p) { #if BOOST_FILESYSTEM_VERSION == 3 return p.filename().string(); #else #if BOOST_VERSION >= 103600 return p.empty() ? std::string() : *--p.end(); #else return p.leaf(); #endif #endif }
bool CreateDirectoriesTransacted(KTMTransaction& trans, const boost::filesystem::path& dir) { if (dir.empty() || FileExistsTransacted(trans, dir.c_str())) { if (!dir.empty() && !boost::filesystem::is_directory(dir)) { // this is an error // TODO log disp, whatever } return false; } // First create branch, by calling ourself recursively CreateDirectoriesTransacted(trans, dir.parent_path()); // Now that parent's path exists, create the directory if (trans.CreateDirectoryExW(nullptr, dir.c_str(), nullptr) == 0) { std::wstring msg = lhWinAPI::GetLastErrorS(); OutputDebugString(msg.c_str()); } return true; }
boost::filesystem::path normalized_path(const boost::filesystem::path& path) { if (path.empty()) return path; fs::path temp; fs::path::iterator start( path.begin() ); fs::path::iterator last( path.end() ); fs::path::iterator stop( last-- ); for ( fs::path::iterator itr( start ); itr != stop; ++itr ) { if (*itr == "." && itr != start && itr != last) continue; // ignore a name and following ".." if (!temp.empty() && *itr == "..") { string lf( temp.filename() ); if (!lf.empty() && lf != "." && lf != "/" # ifdef BOOST_WINDOWS_PATH && !(lf.size() == 2 && lf[1] == ':') # endif && lf != "..") { temp.remove_filename(); continue; } } temp /= *itr; if (itr != last && temp.has_root_path() && fs::is_symlink(temp)) { temp = normalized_path(readlink(temp)); if (temp.filename() == ".") temp = temp.parent_path(); } } if (temp.empty()) temp /= "."; return temp; }
static std::string augeasPath(const fs::path &confPath, const std::string §ion, const char *option) { assert(!confPath.empty()); assert(!section.empty()); assert(option != NULL); std::stringstream valuepath; valuepath << "/files"; valuepath << confPath.string(); valuepath << "/"; valuepath << section; valuepath << "/"; valuepath << option; return valuepath.str(); }
std::vector<std::string> filestorage::get_file_list(const boost::filesystem::path &path) { std::vector<std::string> file_list; if (!path.empty()) { fs::path apk_path(path); fs::recursive_directory_iterator end; for (fs::recursive_directory_iterator i(apk_path); i != end; ++i) { const fs::path cp = (*i); std::string filename = extract_filename(cp.native()); file_list.push_back(filename); } } return file_list; }