本文整理汇总了C++中poco::File::exists方法的典型用法代码示例。如果您正苦于以下问题:C++ File::exists方法的具体用法?C++ File::exists怎么用?C++ File::exists使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类poco::File
的用法示例。
在下文中一共展示了File::exists方法的12个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: OpenAllLibraries
/** Opens all suitable DLLs on a given path.
* @param filePath :: The filepath to the directory where the libraries are.
* @param isRecursive :: Whether to search subdirectories.
* @return The number of libraries opened.
*/
int LibraryManagerImpl::OpenAllLibraries(const std::string &filePath,
bool isRecursive) {
g_log.debug() << "Opening all libraries in " << filePath << "\n";
int libCount = 0;
// validate inputs
Poco::File libPath;
try {
libPath = Poco::File(filePath);
} catch (...) {
return libCount;
}
if (libPath.exists() && libPath.isDirectory()) {
DllOpen::addSearchDirectory(filePath);
// Iteratate over the available files
Poco::DirectoryIterator end_itr;
for (Poco::DirectoryIterator itr(libPath); itr != end_itr; ++itr) {
const Poco::Path &item = itr.path();
if (item.isDirectory()) {
if (isRecursive) {
libCount += OpenAllLibraries(item.toString());
}
} else {
if (skip(item.toString()))
continue;
if (loadLibrary(item.toString())) {
++libCount;
}
}
}
} else {
g_log.error("In OpenAllLibraries: " + filePath + " must be a directory.");
}
return libCount;
}
示例2: DoExportAll
int CStatsUtil::DoExportAll()
{
Poco::Path inpath(m_inputPath);
Poco::Path outpath;
if( m_outputPath.empty() )
{
outpath = inpath.absolute().makeParent().append(DefExportAllDir);
}
else
{
outpath = Poco::Path(m_outputPath).makeAbsolute();
}
GameStats gstats( m_inputPath, m_langconf );
gstats.Load();
//Test output path
Poco::File fTestOut = outpath;
if( ! fTestOut.exists() )
{
cout << "Created output directory \"" << fTestOut.path() <<"\"!\n";
fTestOut.createDirectory();
}
gstats.ExportAll(outpath.toString());
return 0;
}
示例3: DoExportGameScripts
int CStatsUtil::DoExportGameScripts()
{
//Validate output + input paths
Poco::Path inpath(m_inputPath);
Poco::Path outpath;
if( m_outputPath.empty() )
outpath = inpath.absolute().makeParent().append(DefExportScriptsDir);
else
outpath = Poco::Path(m_outputPath).makeAbsolute();
Poco::File fTestOut = outpath;
if( ! fTestOut.exists() )
{
cout << "Created output directory \"" << fTestOut.path() <<"\"!\n";
fTestOut.createDirectory();
}
else if( ! fTestOut.isDirectory() )
throw runtime_error("CStatsUtil::DoExportGameScripts(): Output path is not a directory!");
//Setup the script handler
GameScripts scripts( inpath.absolute().toString() );
//Convert to XML
scripts.ExportScriptsToXML( outpath.toString() );
return 0;
}
示例4: openLibraries
/**
* Opens suitable DLLs on a given path.
* @param libpath A Poco::File object pointing to a directory where the
* libraries are.
* @param loadingBehaviour Control how libraries are searched for
* @param excludes If not empty then each string is considered as a substring
* to search within each library to be opened. If the substring is found then
* the library is not opened.
* @return The number of libraries opened.
*/
int LibraryManagerImpl::openLibraries(
const Poco::File &libpath,
LibraryManagerImpl::LoadLibraries loadingBehaviour,
const std::vector<std::string> &excludes) {
int libCount(0);
if (libpath.exists() && libpath.isDirectory()) {
// Iterate over the available files
Poco::DirectoryIterator end_itr;
for (Poco::DirectoryIterator itr(libpath); itr != end_itr; ++itr) {
const Poco::File &item = *itr;
if (item.isFile()) {
if (shouldBeLoaded(itr.path().getFileName(), excludes))
libCount += openLibrary(itr.path(), itr.path().getFileName());
else
continue;
} else if (loadingBehaviour == LoadLibraries::Recursive) {
// it must be a directory
libCount += openLibraries(item, LoadLibraries::Recursive, excludes);
}
}
} else {
g_log.error("In OpenAllLibraries: " + libpath.path() +
" must be a directory.");
}
return libCount;
}
示例5: enableFileLogging
void Logger::enableFileLogging(const std::string& fileName, int level)
{
Mutex::ScopedLock lock(loggerMutex);
Logger::setLevel(level);
// close the current file log and re-create it.
disableFileLogging();
if (!simpleFileChannel)
{
std::string realName;
// figure out what file name to use
if (fileName.length() == 0) {
// none given, use one from config.
realName = Config::getString(Config::LOGGER_LOG_FILE_PATH);
} else {
realName = fileName;
}
if (realName.length() == 0) {
// default log name.
realName = joinPath(getTempDir(), "roadrunner.log");
} else {
// expand any env vars and make absolute path.
realName = Poco::Path::expand(realName);
Poco::Path path(realName);
realName = path.makeAbsolute().toString();
}
// check if the path is writable
Poco::Path p(realName);
Poco::File fdir = p.parent();
if(!fdir.exists())
{
realName = joinPath(getTempDir(), "roadrunner.log");
Log(Logger::LOG_ERROR) << "The specified log file directory path, "
<< fdir.path() << " does not exist, using default log file path: "
<< realName;
}
SplitterChannel *splitter = getSplitterChannel();
simpleFileChannel = new SimpleFileChannel();
simpleFileChannel->setProperty("path", realName);
simpleFileChannel->setProperty("rotation", "never");
logFileName = simpleFileChannel->getProperty("path");
splitter->addChannel(simpleFileChannel);
simpleFileChannel->release();
}
}
示例6: unlink_directory
void unlink_directory()
{
if ( directory.exists() && directory.isDirectory() )
{
try
{
directory.remove(true);
}
catch(Poco::Exception &e)
{
std::cout << e.displayText() << std::endl;
}
}
}
示例7: initialize
/**
* Module initialization function. Takes a string as input that allows
* arguments to be passed into the module.
* @param arguments Tells the module which
*/
TskModule::Status TSK_MODULE_EXPORT initialize(const char* arguments)
{
magicHandle = magic_open(MAGIC_NONE);
if (magicHandle == NULL) {
LOGERROR("FileTypeSigModule: Error allocating magic cookie.");
return TskModule::FAIL;
}
//Attempt to load magic database from default places on Linux.
//Don't bother trying magic_load() for defaults on win32 because it will always cause an exception instead of gracefully returning.
#ifndef TSK_WIN32
/* Load the default magic database, which is found in this order:
1. MAGIC env variable
2. $HOME/.magic.mgc (or $HOME/.magic dir)
3. /usr/share/misc/magic.mgc (or /usr/share/misc/magic dir) (unless libmagic was build configured abnormally)
*/
if (magic_load(magicHandle, NULL)) {
std::stringstream msg;
msg << "FileTypeSigModule: Error loading default magic file: " << magic_error(magicHandle);
LOGERROR(msg.str());
//don't return, just fall through to the default loading below
} else {
return TskModule::OK;
}
#endif
//Load the magic database file in the repo
std::string path = GetSystemProperty(TskSystemProperties::MODULE_CONFIG_DIR) + Poco::Path::separator() + MODULE_NAME + Poco::Path::separator() + "magic.mgc";
Poco::File magicFile = Poco::File(path);
if (magicFile.exists() == false) {
std::stringstream msg;
msg << "FileTypeSigModule: Magic file not found: " << path;
LOGERROR(msg.str());
return TskModule::FAIL;
}
if (magic_load(magicHandle, path.c_str())) {
std::stringstream msg;
msg << "FileTypeSigModule: Error loading magic file: " << magic_error(magicHandle) << GetSystemProperty(TskSystemProperties::MODULE_CONFIG_DIR);
LOGERROR(msg.str());
return TskModule::FAIL;
}
return TskModule::OK;
}
示例8: FileNotFoundException
SharedMemoryImpl::SharedMemoryImpl(const Poco::File& file, SharedMemory::AccessMode mode, const void*):
_name(file.path()),
_memHandle(INVALID_HANDLE_VALUE),
_fileHandle(INVALID_HANDLE_VALUE),
_size(0),
_mode(PAGE_READONLY),
_address(0)
{
if (!file.exists() || !file.isFile())
throw FileNotFoundException(_name);
_size = static_cast<DWORD>(file.getSize());
DWORD shareMode = FILE_SHARE_READ | FILE_SHARE_WRITE;
DWORD fileMode = GENERIC_READ;
if (mode == SharedMemory::AM_WRITE)
{
_mode = PAGE_READWRITE;
fileMode |= GENERIC_WRITE;
}
#if defined (POCO_WIN32_UTF8)
std::wstring utf16name;
UnicodeConverter::toUTF16(_name, utf16name);
_fileHandle = CreateFileW(utf16name.c_str(), fileMode, shareMode, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
#else
_fileHandle = CreateFileA(_name.c_str(), fileMode, shareMode, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
#endif
if (_fileHandle == INVALID_HANDLE_VALUE)
throw OpenFileException("Cannot open memory mapped file", _name);
_memHandle = CreateFileMapping(_fileHandle, NULL, _mode, 0, 0, NULL);
if (!_memHandle)
{
CloseHandle(_fileHandle);
_fileHandle = INVALID_HANDLE_VALUE;
throw SystemException("Cannot map file into shared memory", _name);
}
map();
}
示例9: FileNotFoundException
SharedMemoryImpl::SharedMemoryImpl(const Poco::File& file, SharedMemory::AccessMode mode, const void* addrHint):
_size(0),
_fd(-1),
_address(0),
_access(mode),
_name(file.path()),
_fileMapped(true),
_server(false)
{
if (!file.exists() || !file.isFile())
throw FileNotFoundException(file.path());
_size = file.getSize();
int flag = O_RDONLY;
if (mode == SharedMemory::AM_WRITE)
flag = O_RDWR;
_fd = ::open(_name.c_str(), flag);
if (-1 == _fd)
throw OpenFileException("Cannot open memory mapped file", _name);
map(addrHint);
}
示例10: initialize
void BaseDaemon::initialize(Application& self)
{
task_manager.reset(new Poco::TaskManager);
ServerApplication::initialize(self);
bool is_daemon = config().getBool("application.runAsDaemon", false);
if (is_daemon)
{
/** При создании pid файла и поиске конфигурации, будем интерпретировать относительные пути
* от директории запуска программы.
*/
std::string path = Poco::Path(config().getString("application.path")).setFileName("").toString();
if (0 != chdir(path.c_str()))
throw Poco::Exception("Cannot change directory to " + path);
}
/// Считаем конфигурацию
reloadConfiguration();
/// В случае падения - сохраняем коры
{
struct rlimit rlim;
if (getrlimit(RLIMIT_CORE, &rlim))
throw Poco::Exception("Cannot getrlimit");
/// 1 GiB. Если больше - они слишком долго пишутся на диск.
rlim.rlim_cur = config().getUInt64("core_dump.size_limit", 1024 * 1024 * 1024);
if (setrlimit(RLIMIT_CORE, &rlim))
{
std::string message = "Cannot set max size of core file to " + std::to_string(rlim.rlim_cur);
#if !defined(ADDRESS_SANITIZER) && !defined(THREAD_SANITIZER)
throw Poco::Exception(message);
#else
/// Не работает под address/thread sanitizer. http://lists.llvm.org/pipermail/llvm-bugs/2013-April/027880.html
std::cerr << message << std::endl;
#endif
}
}
/// This must be done before any usage of DateLUT. In particular, before any logging.
if (config().has("timezone"))
{
if (0 != setenv("TZ", config().getString("timezone").data(), 1))
throw Poco::Exception("Cannot setenv TZ variable");
tzset();
}
std::string log_path = config().getString("logger.log", "");
if (!log_path.empty())
log_path = Poco::Path(log_path).setFileName("").toString();
if (is_daemon)
{
/** Переназначим stdout, stderr в отдельные файлы в директориях с логами.
* Некоторые библиотеки пишут в stderr в случае ошибок или в отладочном режиме,
* и этот вывод иногда имеет смысл смотреть даже когда программа запущена в режиме демона.
* Делаем это до buildLoggers, чтобы ошибки во время инициализации логгера, попали в эти файлы.
*/
if (!log_path.empty())
{
std::string stdout_path = log_path + "/stdout";
if (!freopen(stdout_path.c_str(), "a+", stdout))
throw Poco::OpenFileException("Cannot attach stdout to " + stdout_path);
std::string stderr_path = log_path + "/stderr";
if (!freopen(stderr_path.c_str(), "a+", stderr))
throw Poco::OpenFileException("Cannot attach stderr to " + stderr_path);
}
/// Создадим pid-file.
if (is_daemon && config().has("pid"))
pid.seed(config().getString("pid"));
}
buildLoggers();
if (is_daemon)
{
/** Сменим директорию на ту, куда надо писать core файлы.
* Делаем это после buildLoggers, чтобы не менять текущую директорию раньше.
* Это важно, если конфиги расположены в текущей директории.
*/
std::string core_path = config().getString("core_path", "");
if (core_path.empty())
core_path = getDefaultCorePath();
tryCreateDirectories(&logger(), core_path);
Poco::File cores = core_path;
if (!(cores.exists() && cores.isDirectory()))
{
core_path = !log_path.empty() ? log_path : "/opt/";
tryCreateDirectories(&logger(), core_path);
}
if (0 != chdir(core_path.c_str()))
throw Poco::Exception("Cannot change directory to " + core_path);
//.........这里部分代码省略.........
示例11: verifyContent
// ---
bool VSWAEImportContentWindow::verifyContent ()
{
// By default the verification will be true...
bool result = true;
// Switch off all the warning indicators...
switchOffWarnings ();
// First of all, it verifies all the mandatoty fields
// are introduced. If not the result will be nok.
if (_name -> text () == QString (__NULL_STRING__) ||
_implementationFile -> fileName () == QString (__NULL_STRING__) ||
_type -> currentText () == QString (__NULL_STRING__))
result &= false;
// If the name introduce already exists...
// Then a indication is switched on, and the ok button woill not be enabled...
// But only if something has been introduced.
if (_name -> text () != QString (__NULL_STRING__))
{
bool nameExists = (_contentNames.indexOf (_name -> text ()) != -1);
if (nameExists) result &= false;
_nameTF -> setPixmap (QPixmap (nameExists ?
":/VSWAdvancedEditor/Resources/Error.png" : ":/VSWAdvancedEditor/Resources/Ok.png"));
}
// If the definition directory is not a directory o the directory is not
// contained in the basic path, then there is mistake...
if (_definitionDirName -> dirName () != QString (__NULL_STRING__) &&
_name -> text () != QString (__NULL_STRING__))
{
bool isValidDir = validateDir (_definitionDirName -> dirName ());
Poco::File defFile = Poco::File ((_definitionDirName -> dirName () + QString (__PATH_SEPARATOR__) +
_name -> text () + QString (".xml")).toStdString ());
if (!isValidDir) result &= false;
_definitionDirNameTF -> setPixmap (QPixmap (isValidDir ?
":/VSWAdvancedEditor/Resources/Ok.png" : ":/VSWAdvancedEditor/Resources/Error.png"));
if (isValidDir && defFile.exists ()) // Being valid, the definition file already exists...
_definitionDirNameTF -> setPixmap (QPixmap (":/VSWAdvancedEditor/Resources/Warning.png"));
}
// If the implementation directory is not a directory o the directory is not
// contained in the basic path, then there is mistake...
if (_implementationDirName -> dirName () != QString (__NULL_STRING__) &&
_name -> text () != QString (__NULL_STRING__))
{
QString iF = _implementationFile -> fileName ();
#ifdef __WINDOWSPLATFORM__
iF.replace ("/","\\");
#endif
bool isValidDir = validateDir (_implementationDirName -> dirName ());
Poco::File defFile = Poco::File ((_implementationDirName -> dirName () + QString (__PATH_SEPARATOR__) +
QString (onlyFileName (iF.toStdString ()).c_str ())).toStdString ());
if (!isValidDir) result &= false;
_implementationDirNameTF -> setPixmap (QPixmap (isValidDir ?
":/VSWAdvancedEditor/Resources/Ok.png" : ":/VSWAdvancedEditor/Resources/Error.png"));
if (isValidDir && defFile.exists ()) // Being valid, the implementation file already exists...
_implementationDirNameTF -> setPixmap (QPixmap (":/VSWAdvancedEditor/Resources/Warning.png"));
}
// Test also the destination of the ocon name,
// to show a warning icon if an element with the same name already exists in the destination...
if (_implementationDirName -> dirName () != QString (__NULL_STRING__) &&
_iconFile -> fileName () != QString (__NULL_STRING__))
{
QString iF = _iconFile -> fileName ();
#ifdef __WINDOWSPLATFORM__
iF.replace ("/","\\");
#endif
bool isValidDir = validateDir (_implementationDirName -> dirName ());
Poco::File defFile = Poco::File ((_implementationDirName -> dirName () + QString (__PATH_SEPARATOR__) +
QString (onlyFileName (iF.toStdString ()).c_str ())).toStdString ());
if (!isValidDir) result &= false;
_iconFileTF -> setPixmap (QPixmap (isValidDir ?
":/VSWAdvancedEditor/Resources/Ok.png" : ":/VSWAdvancedEditor/Resources/Error.png"));
if (isValidDir && defFile.exists ()) // Being valid, the implementation file already exists...
_iconFileTF -> setPixmap (QPixmap (":/VSWAdvancedEditor/Resources/Warning.png"));
}
// The same with the resumen file...
if (_implementationDirName -> dirName () != QString (__NULL_STRING__) &&
_resumeFile -> fileName () != QString (__NULL_STRING__))
{
QString iF = _resumeFile -> fileName ();
#ifdef __WINDOWSPLATFORM__
iF.replace ("/","\\");
#endif
bool isValidDir = validateDir (_implementationDirName -> dirName ());
Poco::File defFile = Poco::File ((_implementationDirName -> dirName () + QString (__PATH_SEPARATOR__) +
QString (onlyFileName (iF.toStdString ()).c_str ())).toStdString ());
if (!isValidDir) result &= false;
_resumeFileTF -> setPixmap (QPixmap (isValidDir ?
":/VSWAdvancedEditor/Resources/Ok.png" : ":/VSWAdvancedEditor/Resources/Error.png"));
if (isValidDir && defFile.exists ()) // Being valid, the implementation file already exists...
_resumeFileTF -> setPixmap (QPixmap (":/VSWAdvancedEditor/Resources/Warning.png"));
}
//.........这里部分代码省略.........
示例12: configurationFilePath
/**
* Module initialization function. The initialization arguments string should
* provide the path of a module configuration file that defines what files
* are interesting. If the empty string is passed to this function, the module
* assumes a default config file is present in the output directory.
*
* @param args Path of the configuration file that defines what files are
* interesting, may be set to the empty string.
* @return TskModule::OK on success, TskModule::FAIL otherwise.
*/
TSK_MODULE_EXPORT TskModule::Status initialize(const char* arguments)
{
TskModule::Status status = TskModule::OK;
const std::string MSG_PREFIX = "InterestingFilesModule::initialize : ";
try
{
// Make sure the file sets are cleared in case initialize() is called more than once.
fileSets.clear();
configFilePath.assign(arguments);
if (configFilePath.empty())
{
// Use the default config file path.
Poco::Path configurationFilePath(Poco::Path::forDirectory(GetSystemProperty(TskSystemProperties::MODULE_CONFIG_DIR)));
configurationFilePath.pushDirectory(MODULE_NAME);
configurationFilePath.setFileName(DEFAULT_CONFIG_FILE_NAME);
configFilePath = configurationFilePath.toString();
}
// Compile the contents of the config file into interesting file set definitions.
Poco::File configFile = Poco::File(configFilePath);
if (configFile.exists())
{
std::ifstream configStream(configFile.path().c_str());
if (configStream)
{
Poco::XML::InputSource inputSource(configStream);
Poco::AutoPtr<Poco::XML::Document> configDoc = Poco::XML::DOMParser().parse(&inputSource);
Poco::XML::Element * rootElement = configDoc->documentElement();
if (rootElement == NULL)
{
std::ostringstream msg;
msg << MSG_PREFIX << "Root element of config file is NULL.";
throw TskException(msg.str());
}
const std::string& ignoreKnownValue = Poco::XML::fromXMLString(rootElement->getAttribute(IGNORE_KNOWN_TAG));
if (!ignoreKnownValue.empty())
{
knownType = parseKnownType(ignoreKnownValue);
ignoreKnown = true;
}
Poco::AutoPtr<Poco::XML::NodeList> fileSetDefinitions = configDoc->getElementsByTagName(INTERESTING_FILE_SET_ELEMENT_TAG);
for (unsigned long i = 0; i < fileSetDefinitions->length(); ++i)
{
compileInterestingFilesSet(fileSetDefinitions->item(i));
}
}
else
{
std::ostringstream msg;
msg << MSG_PREFIX << "failed to open config file '" << configFilePath << "'";
throw TskException(msg.str());
}
}
else
{
std::ostringstream msg;
msg << MSG_PREFIX << "config file'" << configFilePath << "' does not exist";
LOGERROR(msg.str());
}
// Log the configuration.
std::ostringstream msg;
msg << MSG_PREFIX << "configured with " << fileSets.size() << " interesting file set definitions from '" << configFilePath << "'";
LOGINFO(msg.str());
}
catch (TskException &ex)
{
status = TskModule::FAIL;
configFilePath.clear();
std::ostringstream msg;
msg << MSG_PREFIX << "TskException: " << ex.message();
LOGERROR(msg.str());
}
catch (Poco::Exception &ex)
{
status = TskModule::FAIL;
configFilePath.clear();
std::ostringstream msg;
msg << MSG_PREFIX << "Poco::Exception: " << ex.displayText();
LOGERROR(msg.str());
}
catch (std::exception &ex)
{
status = TskModule::FAIL;
//.........这里部分代码省略.........