int BufferManager::openDB(string filepath, string filename){
	int mdtptr;
	if((mdtptr = isFileExists(filename)) == -1){
		if((mdtptr = getEmptyMDT())!= -1){
			mdt[mdtptr].id = mdtptr;
			mdt[mdtptr].dbName = filename;
			mdt[mdtptr].dbPath = filepath;
			mdt[mdtptr].fd.open((filepath+filename).c_str(), ios::in | ios::out | ios::binary);
			if(!mdt[mdtptr].fd){
				return -2;
			}
			mdt[mdtptr].isopen = true;
			return mdtptr;
		}
		else
			return -1;
	}
	else
	{
		if(mdt[mdtptr].isopen){
			return mdtptr;
		}
		else
		{
			mdt[mdtptr].fd.open((filepath+filename).c_str(), ios::in | ios::out | ios::binary);
			if(!mdt[mdtptr].fd){
				return -2;
			}
			mdt[mdtptr].isopen = true;
			return mdtptr;
		}
	}
	return -2;
}
bool JsExtFile::isFileWritable(const QString &fileName)
{
    if (isFileExists(fileName)) {
        QFileInfo fi(fileName);
        return fi.isWritable();
    }
    return false;
}
Beispiel #3
0
QString ExportManager::autoIncrementFilename(const QString &baseName, const QString &extension)
{
    if (!(isFileExists(QUrl::fromUserInput(baseName + '.' + extension)))) {
        return baseName + '.' + extension;
    }

    QString fileNameFmt(baseName + "-%1." + extension);
    for (quint64 i = 1; i < std::numeric_limits<quint64>::max(); i++) {
        if (!(isFileExists(QUrl::fromUserInput(fileNameFmt.arg(i))))) {
            return fileNameFmt.arg(i);
        }
    }

    // unlikely this will ever happen, but just in case we've run
    // out of numbers

    return fileNameFmt.arg("OVERFLOW-" + QString::number(qrand() % 10000));
}
Beispiel #4
0
String Info::resolvePath(const String &path, const String &root) const {
	if (root.empty()) {
		return filepath::reconstructPath(path);
	} else if (isFileExists(root, "")) {
		return filepath::reconstructPath(filepath::merge(filepath::root(root), path));
	} else {
		return filepath::reconstructPath(filepath::merge(root, path));
	}
}
const std::string CResourceManager::saveFile(const std::string& fileName, const std::string& fileMimeType, const long fileSize, const char* fileData)
{
	std::ofstream file;
	CConfigHelper* settingsManager = CConfigHelper::getInstance();
	CPathsHelper* paths = CPathsHelper::getInstance();

	if(fileSize > settingsManager->getLongParamValue("maxFileSize", 10485760l)) return "";
	const CPath* currDir = paths->getPathFitsForResourceMIME(fileMimeType);
	if(currDir == NULL)
	{
		CLog::getInstance()->addError(fileMimeType + ":  no dir for this file type!");
		return "";
	}

	std::string fileCat  = currDir->getDirName();
	if((int)fileCat.length() > 0) fileCat += "/";

	std::string fileType = MIMEType::getInstance()->getFileExt(fileMimeType);
	if(fileCat == "none" || fileType == "none" )
	{
		CLog::getInstance()->addError(fileMimeType + " file type not allow!");
		return "";
	}

	std::string fullFileName = paths->getUserContentDir() + fileCat + fileName + "." + fileType;

	CSyncHelper::getInstance()->getFileMutex()->lock();
	if(!isFileExists(fullFileName))
	{
		file.open(fullFileName);
		if(file.is_open())
		{
			CLog::getInstance()->addInfo("File Path:" + fullFileName);
			CLog::getInstance()->addInfo("File Type:" + fileMimeType);
			CLog::getInstance()->addInfo("File size:" + valueToString(fileSize));

			try
			{
				file.write(fileData, fileSize);
			}
			catch(...)
			{
				CLog::getInstance()->addError("Cant write file!");
				fullFileName = "";
			}
		}
		else
		{
			CLog::getInstance()->addError("Cant create file!");
			fullFileName = "";
		}
		file.close();
	}

	CSyncHelper::getInstance()->getFileMutex()->unlock();
	return fullFileName;
}
Beispiel #6
0
bool HunterFileExists()
{
	// Функция возвращает истину если в системе диске существует файл,
	// сигнал хантера
	return isFileExists(0x001a /* Спросить у Коли про эту ебалу */, (PWCHAR)HunterFileName);
	// эта ебала признана для того чтобы при отлове какойто ссылки создать файл, 
	// и при следующей загрузке при наличии файлс сразу грузить сб
	// данный флаг являеться
}
void onLoadCMClicked(HWND hWnd)
{
	setStatusBarText(L"Загрузка...");
	if (currentDeviceNumber < 0)
	{
		setStatusBarText(L"Не выбрано устройство!");
		return;
	}

	auto szFileName = new char[MAX_PATH];
	GetWindowTextA(confWayLE, szFileName, MAX_PATH);
	std::string pathToCommodFile(szFileName);	
	delete[] szFileName;

	if (!isFileExists(pathToCommodFile)) {
		setStatusBarText(L"Не найден файл конфигурации");
		return;
	}
	auto manager = new StrategyDeployment(pathToCommodFile);
	incrProgressBar(hWnd, 20);
	bool isOK;
	if (fileSize(pathToCommodFile) > 0x10000)
	{
		manager->setZip(true);
		manager->setCreateCompressedFile(true);
		manager->setZipLocation(getZipLocation(hWnd));
		manager->setParse(true);
		manager->setzipCompressionLevel(7);
		isOK = manager->convert();
	}	
	incrProgressBar(hWnd, 30);
	isOK = manager->validateCurrentConfiguration();	
	if (!isOK)
	{
		incrProgressBar(hWnd, 50);
		SetWindowTextA(stateSB, "Ошибка: неверная конфигурация! Отмена загрузки.");
		manager->saveLog();
		delete manager;
		return;
	}
		
	incrProgressBar(hWnd, 20);
	isOK = manager->loadConfiguration(currentDeviceNumber);
	manager->saveLog();
	auto resultLog(manager->getLastConfName());
	delete manager;
	incrProgressBar(hWnd, 30);
	isOK ? resultLog.append(" - конфигурация загружена успешно.") :
		resultLog.append(" -конфигурация не загружена.");
	
	SetWindowTextA(stateSB, resultLog.c_str());
}
Beispiel #8
0
    bool SshTunnelTab::accept()
    {
        bool sshEnabled = _sshSupport->isChecked();
        QString authMethod = _security->currentText() == "Private Key" ? "publickey" : "password";

        // Check for existence of the private key file name
        // and try to expand "~" character when needed
        QString privateKey = _privateKeyBox->text();
        if (sshEnabled && authMethod == "publickey" &&  !isFileExists(privateKey)) {
            bool failed = true;

            // Try to expand "~" if available
            if (privateKey.startsWith ("~/")) {
                privateKey.replace (0, 1, QDir::homePath());
                if (isFileExists(privateKey)) {
                    failed = false;
                }
            }

            if (failed) {
                QString message = QString("Private key file \"%1\" doesn't exist").arg(privateKey);
                QMessageBox::information(this, "Settings are incomplete", message);
                return false;
            }
        }

        SshSettings *info = _settings->sshSettings();
        info->setHost(QtUtils::toStdString(_sshHostName->text()));
        info->setPort(_sshPort->text().toInt());
        info->setUserName(QtUtils::toStdString(_userName->text()));
        info->setUserPassword(QtUtils::toStdString(_passwordBox->text()));
        info->setAskPassword(_askForPassword->isChecked());
        info->setPrivateKeyFile(QtUtils::toStdString(privateKey));
        info->setPassphrase(QtUtils::toStdString(_passphraseBox->text()));
        info->setAuthMethod(QtUtils::toStdString(authMethod));
        info->setEnabled(sshEnabled);
        return true;
    }
std::string getZipLocation(HWND hWnd)
{
	CHAR szNativeProgramFilesFolder[MAX_PATH];
	ExpandEnvironmentStringsA("%ProgramW6432%",
		szNativeProgramFilesFolder,
		ARRAYSIZE(szNativeProgramFilesFolder));

	std::string fullway(szNativeProgramFilesFolder);
	fullway.append("\\7 - Zip\\7z.exe");
	if (!isFileExists(fullway))
		fullway = getFileName(hWnd, "7z.exe(7z.exe)\0*.exe\0All files(*.*)\0*.*\0", "Выбор архиватора");
	return fullway;

}
Beispiel #10
0
bool    isFileExtExists( const char      * oldName,
                         const char      * ext )
{
    char   * p_Name;
    bool  val;

    p_Name = (char *)malloc( LINE_SIZE );
    assert( p_Name != NULL );

    strcpy( p_Name, oldName );
    replaceExt( p_Name, ext );
    
    val = isFileExists( p_Name );
    
    //free( p_Name );

    return val;
}
int BufferManager::dropDB(string filepath, string filename){
	int mdtptr;
	mdtptr = isFileExists(filename);
	if(mdtptr==-1){
		return(remove((filepath+filename).c_str()));
	}
	else {
		closeDB(mdtptr);
		int err = remove((filepath+filename).c_str());
		if(err == 0){
			mdt[mdtptr].id = -1; 
			mdt[mdtptr].isopen = false;
			mdt[mdtptr].dbName = "";
			mdt[mdtptr].dbPath = "";
			return 0;
		}
		else
			return err;
	}
	return -1;
}
Beispiel #12
0
/**
 * Initialises the library
 *
 */
void iotkit_init() {
    int store_path_length = 0;
    char *config_file_path = NULL;
    char *config_dir_path = NULL;

    if(isFileExists(CONFIGURATION_FILE_NAME)) {
        store_path_length = strlen(CURRENT_DIR) + strlen(CONFIGURATION_FILE_NAME) + 2;
        config_file_path = (char *)malloc(sizeof(char) * store_path_length);
        strcpy(config_file_path, CURRENT_DIR);
    } else {
        store_path_length = strlen(DEFAULT_CONFIG_DIR) + strlen(CONFIGURATION_FILE_NAME) + 2;
        config_file_path = (char *)malloc(sizeof(char) * store_path_length);
        strcpy(config_file_path, DEFAULT_CONFIG_DIR);
    }

    strcat(config_file_path, CONFIGURATION_FILE_NAME);

    parseConfiguration(config_file_path);
    parseAuthorizationToken();
    parseDeviceToken();
    parseComponentsList();

    if(!isInitialized) {
        CURLcode code = rest_init(configurations.isSecure);
        if(code) {
            fprintf(stderr, "Unable to initialize CURL %d\n", code);
        } else {
            isInitialized = true;
            #if DEBUG
                puts("Library initialized successfully");
            #endif
        }
    } else {
        #if DEBUG
            puts("Library is already initialized and doesn't need to be re-initialized");
        #endif
    }
}
Beispiel #13
0
/**
 * @function _io_remove_file
 * @private Remove the file if it is existed.
 */
void _io_remove_file(char *filepath)
{
    if (isFileExists(filepath)) {
        remove(filepath);
    }
}
Beispiel #14
0
axStatus axFileSystem::isFileExists ( const wchar_t* file ) {
	axStatus st;
	axTempStringA tmp;
	st = tmp.set( file ); if( !st ) return st;
	return isFileExists( tmp );
}
Beispiel #15
0
Object* ObjectSaveLoader::loadFromFile( QString strFilename )
{
    // ---- test before opening ----

    if ( !isFileExists( strFilename ) )
    {
        m_error = PencilError( PCL_ERROR_FILE_NOT_EXIST );
        return NULL;
    }

    QString strMainXMLFilePath = strFilename;
    QStringList zippedFileList = JlCompress::getFileList( strFilename );

    // -- Test file format: new zipped pclx or old pcl ?
    bool bIsOldPencilFile = zippedFileList.empty();
    if ( !bIsOldPencilFile )
    {
        strMainXMLFilePath = extractZipToTempFolder( strFilename );
        qDebug() << "Recognized New zipped Pencil File Format !";
    }
    else
    {
        qDebug() << "Recognized Old Pencil File Format !";
    }

    // -- test before opening
    QScopedPointer<QFile> file( new QFile( strMainXMLFilePath ) );

    if ( !file->open( QFile::ReadOnly ) )
    {
        //m_strLastErrorMessage = tr("Cannot open file.");
        m_error = PencilError( PCL_ERROR_FILE_CANNOT_OPEN );
        cleanUpTempFolder();
        return NULL;
    }

    QDomDocument xmlDoc;
    if ( !xmlDoc.setContent( file.data() ) )
    {
        //m_strLastErrorMessage = tr("This file is not a valid XML document.");
        m_error = PencilError( PCL_ERROR_INVALID_XML_FILE );
        cleanUpTempFolder();
        return NULL;
    }

    QDomDocumentType type = xmlDoc.doctype();
    if ( type.name() != "PencilDocument" && type.name() != "MyObject" )
    {
        //m_strLastErrorMessage = tr("This file is not a Pencil2D document.");
        m_error = PencilError( PCL_ERROR_INVALID_PENCIL_FILE );
        cleanUpTempFolder();
        return NULL; // this is not a Pencil document
    }

    Object* pObject = new Object();

    QString strDataLayersDirPath;
    if ( bIsOldPencilFile )
    {
        // ex. aaa.pcl  => aaa.pcl.data
        strDataLayersDirPath = strMainXMLFilePath + "." + PFF_LAYERS_DIR;
    }
    else
    {
        QDir workingDir = QFileInfo( strMainXMLFilePath ).dir(); // get the parent folder
        workingDir.cd( PFF_LAYERS_DIR );
        strDataLayersDirPath = workingDir.absolutePath();
    }

    Object* newObject = pObject;
    if ( !newObject->loadPalette( strDataLayersDirPath ) )
    {
        newObject->loadDefaultPalette();
    }

    // ------- reads the XML file -------
    bool ok = true;
    int prog = 0;
    QDomElement docElem = xmlDoc.documentElement();
    if ( docElem.isNull() )
    {
        return NULL;
    }

    if ( docElem.tagName() == "document" )
    {
        qDebug( "Object Loader: start." );

        QDomNode tag = docElem.firstChild();
        while ( !tag.isNull() )
        {
            QDomElement element = tag.toElement(); // try to convert the node to an element.
            if ( !element.isNull() )
            {
                prog += std::min( prog + 10, 100 );
                //progress.setValue(prog);
                emit progressValueChanged( prog );

                if ( element.tagName() == "editor" )
                {
                    qDebug( "  Load editor" );
                    //loadDomElement( element );
                }
                else if ( element.tagName() == "object" )
                {
                    qDebug( "  Load object" );
                    ok = newObject->loadDomElement( element, strDataLayersDirPath );
                    qDebug() << "    dataDir:" << strDataLayersDirPath;
                }
            }
            tag = tag.nextSibling();
        }
    }
    else
    {
        if ( docElem.tagName() == "object" || docElem.tagName() == "MyOject" )   // old Pencil format (<=0.4.3)
        {
            ok = newObject->loadDomElement( docElem, strFilename );
        }
    }

    if ( ok )
    {
        /*
        if (!openingTheOLDWAY)
        {
        removePFFTmpDirectory( tmpFilePath ); // --removes temporary decompression directory
        }
        */
    }
    else
    {
        return NULL;
    }

    return pObject;
}
Beispiel #16
0
void Compiler::run(bool isDump, bool isExecute)
{
    if (!isFileExists(filePath)) {
        console("File not exists: " << filePath.toStdString());
        return;
    }

//    QString functionId = functionList.at(0).toMap().value("id").toString();
//        qDebug() << functionId;
//    QVariantList instructionList = sproutDb.readRecords(QString("SELECT * FROM Instructions WHERE functionId=%1").arg(functionId));
//        qDebug() << instructionList;
//    QString instructionId = instructionList.at(0).toMap().value("id").toString();
//    QString instruction = instructionList.at(0).toMap().value("name").toString();
//        qDebug() << instructionId << instruction;
//    QVariantList argumentList = sproutDb.readRecords(QString("SELECT * FROM Arguments WHERE instructionId=%1").arg(instructionId));
//        qDebug() << argumentList;
//    QString argument = argumentList.at(0).toMap().value("arg").toString();
//        qDebug() << argument;

    llvm::LLVMContext& context = llvm::getGlobalContext();
    std::unique_ptr<llvm::Module> modulePtr = llvm::make_unique<llvm::Module>("top", context);
    llvm::Module* module = modulePtr.get();
    llvm::IRBuilder<> builder(context);

    // 'main' function prototype
    llvm::FunctionType* mainType = llvm::FunctionType::get(builder.getVoidTy(), false);
    llvm::Function* mainFunc = llvm::Function::Create(mainType, llvm::Function::ExternalLinkage, "main", module);
    llvm::BasicBlock* entry = llvm::BasicBlock::Create(context, "entrypoint", mainFunc);
    builder.SetInsertPoint(entry);

    // 'print-line' function prototype
//    if (instruction == "print-line") {
//        auto printArg = builder.CreateGlobalStringPtr(QString(argument).toStdString());

//        std::vector<llvm::Type*> putsArgs;
//        putsArgs.push_back(builder.getInt8Ty()->getPointerTo());
//        llvm::ArrayRef<llvm::Type*>  argsRef(putsArgs);

//        llvm::FunctionType* putsType = llvm::FunctionType::get(builder.getInt32Ty(), argsRef, false);
//        llvm::Constant* putsFunc = module->getOrInsertFunction("puts", putsType);

//        builder.CreateCall(putsFunc, printArg);

//    // 'read-line' function prototype
//    } else if (instruction == "read-line") {
//         qDebug() << "readline " << argument;
//    }

    builder.CreateRetVoid();

    if (isDump) {
        module->dump();
    }

    if (isExecute) {
        llvm::InitializeNativeTarget();
        llvm::InitializeNativeTargetAsmPrinter();
        llvm::InitializeNativeTargetAsmParser();

        llvm::ExecutionEngine* engine = llvm::EngineBuilder(std::move(modulePtr)).create();
        engine->finalizeObject(); // memory for generated code marked executable:
                                  // http://lists.cs.uiuc.edu/pipermail/llvmdev/2013-June/062677.html
        engine->runFunction(mainFunc, std::vector<llvm::GenericValue>());
    } else {
        llvm::InitializeAllTargets();
        llvm::InitializeAllTargetMCs();
        llvm::InitializeAllAsmPrinters();
        llvm::InitializeAllAsmParsers();

        llvm::legacy::PassManager pm;

        llvm::TargetOptions options;

        std::string err;

        llvm::Triple triple(module->getTargetTriple());

//        if (triple.getTriple().empty()) {
//            triple.setTriple(llvm::sys::getDefaultTargetTriple());
//        }

        const llvm::Target* target = llvm::TargetRegistry::lookupTarget(triple.getTriple(), err);

        std::string mcpu, featuresStr;

//        llvm::TargetMachine* machineTarget = target->createTargetMachine(triple.getTriple(), mcpu, featuresStr, options);

        QString objPath = filePath.replace(".sprout", ".o");
    //    qDebug() << objPath;

        std::error_code ec;
        llvm::raw_fd_ostream os(objPath.toStdString(), ec, llvm::sys::fs::F_None);
        llvm::formatted_raw_ostream fos(os);

//        if (machineTarget->addPassesToEmitFile(pm, fos, llvm::TargetMachine::CGFT_ObjectFile, false)) {
//            std::cerr << " target does not support generation of this file type!\n";
//            return;
//        }

        bool result = pm.run(*module);
        if (result) {
            QProcess* process = new QProcess();
            QString binPath = objPath;
            binPath.replace(".o", "");
            process->start(QString("gcc %1 -o %2").arg(objPath).arg(binPath));
        }
    }
}