Beispiel #1
0
void Manga::download(unsigned int chapter)
{
	unsigned int i(1);
	std::list<Chapter>::iterator it(m_chapters.begin());
	while (i < chapter)
	{
		++i;
		++it;
		if (it == m_chapters.end())
		{
			std::cerr<<"Chapter "<<chapter<<" doesn't exist for "<<m_name<<"\n";
			return;
		}
	}
	
	
	char chapter_dir[300];
	sprintf(chapter_dir, "%s %u", m_name.c_str(), chapter);
	
	if (!testing)
	{
		if (!directoryExists("mangas/" + m_name + "/" + chapter_dir))
			createDirectory("mangas/" + m_name + "/" + chapter_dir);
		it->setDir("mangas/" + m_name + "/" + chapter_dir + "/");
	}
	
	
	it->setChapter(chapter);
	it->thDownload();
	
}
void MessageStorage::initialize(char * storageRoot, bool deleteOldQueue)
{
	if(storageRoot == NULL)
	{
		module_debug_strg("cannot work without storage root!");
		return;
	}
	
	strcpy(m_storageRoot, storageRoot);
	
	// mount the actual storage device we use for storing data
	module_debug_strg("mounting storage...");
	if(mountStorage())
		module_debug_strg("storage available!");
	else
		module_debug_strg("storage not available!");
	
	uint8_t cnt = 15;
	
	module_debug_strg("starting speed tests...");
	while(cnt--)
		FATFS_speedTest(8);
	
	module_debug_strg("end of speed tests...");
	
	module_debug_strg("changing to storage root: %s", m_storageRoot);
	// change to storage root
	changeDirectory(m_storageRoot);
	
	module_debug_strg("creating storage subdirs...");
	// create subdirectories
	createDirectory(SUBDIR_QUEUE);
	createDirectory(SUBDIR_AUDIO);
	createDirectory(SUBDIR_LOG);
	
	
	// count list of existing files in storage root,
	module_debug_strg("counting files...");
	
	// count disk files on queue
	m_queueCount = traverseDirectory(SUBDIR_QUEUE, &m_nextMessageSeqNumber, deleteOldQueue);
	
	// traverse audio samples as well to find latest seq number there
	// hardcoded to not remove old files, gut sound is a valuable commodity...
	traverseDirectory(SUBDIR_AUDIO, &m_nextAudioSeqNumber, false);
}
Beispiel #3
0
void Filesystem::createDirectories(const std::string& dir) {
	std::vector<std::string> s(split(dir));
	std::string full;
	for(unsigned i = 0; i < s.size(); i++) {
		full = append(full, s[i]);
		createDirectory(full);
	}
}
Beispiel #4
0
QString NewProjectDialog::fullDirectory() const
{
	QDir dir(location());

	if (createDirectory())
		dir = dir.absoluteFilePath(name());

	return dir.absolutePath();
}
Beispiel #5
0
static int checkDirectory(char * filename) {
    static char * lastDir = NULL;
    static int lastDirLength = 0;
    static int lastDirAlloced = 0;
    int length = strlen(filename);
    char * buf;
    char * chptr;
    int rc = 0;

    buf = alloca(length + 1);
    strcpy(buf, filename);

    for (chptr = buf + length - 1; chptr > buf; chptr--) {
        if (*chptr == '/') break;
    }

    if (chptr == buf) return 0;     /* /filename - no directories */

    *chptr = '\0';                  /* buffer is now just directories */

    length = strlen(buf);
    if (lastDirLength == length && !strcmp(buf, lastDir)) return 0;

    if (lastDirAlloced < (length + 1)) {
        lastDirAlloced = length + 100;
        lastDir = realloc(lastDir, lastDirAlloced);
    }

    strcpy(lastDir, buf);
    lastDirLength = length;

    for (chptr = buf + 1; *chptr; chptr++) {
        if (*chptr == '/') {
            *chptr = '\0';
            rc = createDirectory(buf, 0755);
            *chptr = '/';
            if (rc) return rc;
        }
    }
    rc = createDirectory(buf, 0755);

    return rc;
}
bool InvokeJavascript_OneArg(NPObject *npobj, const char *methodName, const NPVariant &arg, NPVariant *&result) {
  if (!(NPVARIANT_IS_STRING(arg))) {
    return false;
  }

  bool success = false;

  const char *argStringValue = stringFromNpVariant(arg);

  if (!strcmp(methodName, "fileExists")) {
    //fileExists(filename : string) : bool
    success = SetReturnValue(fileExists(argStringValue), *result);
  } else if (!strcmp(methodName, "isDirectory")) {
    //isDirectory(filename : string) : bool
    success = SetReturnValue(isDirectory(argStringValue), *result);
  } else if (!strcmp(methodName, "createDirectory")) {
    if (!createDirectory(argStringValue)) {
      //TODO: Throw a particular exception
      success = false;
    } else {
      success = true;
    }
  } else if (!strcmp(methodName, "getTextFile")) {
    //getTextFile(filename : string) : string
    char *value = NULL;
    size_t len = 0;
    if (getFile(argStringValue, value, len, false)) {
      success = SetReturnValue(value, len, *result);
      delete[] value;
    }
  } else if (!strcmp(methodName, "getBinaryFile")) {
    //getBinaryFile(filename : string) : array<byte>
    char *value = NULL;
    size_t len = 0;
    if (getFile(argStringValue, value, len, true)) {
      success = SetArrayReturnValue(value, len, GetInstance(npobj), result);
      delete[] value;
    }
  } else if (!strcmp(methodName, "removeFile")) {
    //removeFile(filename : string) : void
    success = removeFile(argStringValue);
  } else if (!strcmp(methodName, "listFiles")) {
    //listFiles(filename : string) : array<object>
    std::vector<FileEntry *> *entries;
    if (listFiles(argStringValue, entries)) {
      success = SetArrayReturnValue(*entries, GetInstance(npobj), result);
      deleteFileEntries(entries);
    } else {
      success = false;
    }
  }

  delete[] argStringValue;
  return success;
}
Beispiel #7
0
/*
 * Class:     edu_uw_apl_commons_tsk4j_filesys_FileSystem
 * Method:    dirOpen
 * Signature: (JLjava/lang/String;)Ledu/uw/apl/commons/tsk4j/filesys/Directory;
 */
JNIEXPORT jobject JNICALL 
Java_edu_uw_apl_commons_tsk4j_filesys_FileSystem_dirOpen
(JNIEnv *env, jobject thiz, jlong nativePtr, jstring path ) {

  const char* pathC = (*env)->GetStringUTFChars( env, path, NULL );

  TSK_FS_INFO* info = (TSK_FS_INFO*)nativePtr;
  TSK_FS_DIR* fsDir = tsk_fs_dir_open( info, pathC );

  if( !fsDir ) {
	(*env)->ReleaseStringUTFChars( env, path, pathC );
	return (jobject)NULL;
  }
  TSK_FS_FILE* fsFile = fsDir->fs_file;

  jobject fileMeta = NULL;
  if( fsFile->meta ) {
	fileMeta = createFileMeta( env, fsFile->meta );
	if( !fileMeta ) {
	  tsk_fs_dir_close( fsDir );
	  (*env)->ReleaseStringUTFChars( env, path, pathC );
	  return NULL;
	}
  }

  jobject fileName = NULL;
  if( fsFile->name ) {
	fileName = createFileName( env, fsFile->name );
	if( !fileName ) {
	  tsk_fs_dir_close( fsDir );
	  (*env)->ReleaseStringUTFChars( env, path, pathC );
	  // LOOK: release fileMeta ????
	  return NULL;
	}
  }

  jobject file = createFile( env, fsFile, thiz, fileMeta, fileName ); 
  if( !file ) {
	  tsk_fs_dir_close( fsDir );
	  (*env)->ReleaseStringUTFChars( env, path, pathC );
	  // LOOK: release fileMeta, fileName ????
	  return NULL;
  }
  
  jobject result = createDirectory( env, fsDir, thiz, file );
  if( !result ) {
	  tsk_fs_dir_close( fsDir );
	  (*env)->ReleaseStringUTFChars( env, path, pathC );
	  // LOOK: release fileMeta, fileName, file ????
	  return NULL;
  }

  (*env)->ReleaseStringUTFChars( env, path, pathC );
  return result;
}
Beispiel #8
0
//-----------------------------------------------------------------------------
StatusCode RootHistCnv::RDirectoryCnv::updateRep(IOpaqueAddress* /* pAddress */,
                                                 DataObject* pObject)
//-----------------------------------------------------------------------------
{
  const std::string& loc = pObject->registry()->identifier();
  if ( createDirectory(loc).isSuccess() )   {
    setDirectory(loc);
    return StatusCode::SUCCESS;
  }
  return StatusCode::FAILURE;
}
Beispiel #9
0
int main(void) {
    srand(time(NULL));
    int pid = getpid();
    char *roomsFolder = createDirectory(pid);    
    struct Positions pos = generateRooms(roomsFolder);
    // printf("START_ROOM is %s.\n", startRoom); // Debug
    gameLoop(pos);
    
    free(roomsFolder);
    return 0; 
}
Beispiel #10
0
void GLXOSD::startFrameLogging() {
	Lock lock(&frameLogMutex);
	frameLoggingEnabled = true;
	createDirectory(frameLogDirectory);
	std::stringstream nameStream;
	nameStream << frameLogDirectory << "/glxosd_" << getpid() << "_"
			<< std::time(0) << "_" << frameLogId++ << ".log";
	frameLogFilename = nameStream.str();
	frameLogStream.open(frameLogFilename, std::ofstream::out);
	frameLogMonotonicTimeOffset = getMonotonicTimeNanoseconds();
}
void rspfTempFilename::generate(bool createAsDirectoryFlag)
{
   srand(time(0));
   rspfString tempDirCopy = theTempDir;

   if(tempDirCopy == "")
   {
      tempDirCopy = rspfEnvironmentUtility::instance()->getEnvironmentVariable("TEMP");
      if(tempDirCopy=="")
      {
         tempDirCopy  = rspfEnvironmentUtility::instance()->getEnvironmentVariable("TMP");
      }
      if(tempDirCopy == "")
      {
         if(rspfFilename("/tmp").exists())
         {
            tempDirCopy = "/tmp";
         }
      }
   }

   int count = 0;
   int randNumber1 = rand();
   rspfFilename prefixDir = rspfFilename(tempDirCopy);
   rspfFilename result = prefixDir.dirCat(thePrefix+
                                           rspfString::toString(randNumber1));
   
   while((count < RAND_MAX)&&result.exists())
   {
      randNumber1 = rand();
      result = prefixDir.dirCat(thePrefix+
                                rspfString::toString(randNumber1));
      
      ++count;
   }

   if(theExtension != "")
   {
      result = result.setExtension(theExtension);
   }
   *((rspfFilename*)this) = result;
   if(result != "")
   {
      if(createAsDirectoryFlag)
      {
         createDirectory();
      }
      else
      {
         std::ofstream out(result.c_str());
         out.close();
      }
   }
}
Beispiel #12
0
int mkdir_main(int argc, char **argv) {
	directory* elem = getDirectoryFromName(argv[1]);
	if (elem == NULL) {
		elem = createDirectory(argv[1]);
		allocateDirectory(elem);
		addDirectoryChild(elem, currentdir);
	} else {
		printk("No se puede crear el directorio '%s': Ya existe\n", argv[1]);
	}
	return 0;
}
Beispiel #13
0
    // -------------------------
    //	Check if the directory exists, if not create the directory.
    //	This function will create a new directory if the image is the first
    //	image taken for a specific day
    bool FileManager::createDirectoryIfNotExists(std::string & dir)
    {
        struct stat info;
        std::string path = m_baseDir + "/" + dir;
	   // -------------------------
        // If directory doesn't exists, can't open.
        if(stat(path.c_str(), &info ) != 0)
        {
            return createDirectory(path);
        }
        return false;
    }
int main(int argc, char* argv[]) {
    try {
        Util::getInstance();
        
        createDirectory(DIRECTORY_ROBOT_16);
        createDirectory(DIRECTORY_VENDEDOR);
        createDirectory(DIRECTORY_CLIENTE);
        createDirectory(DIRECTORY_DESPACHO);

        createIPCs();

        Util::createProcess("Cliente", 3, 1);
    }
    catch (Exception & e) {
        Logger::getInstance().logMessage(Logger::ERROR,
        e.get_error_description().c_str());
        return -1;
    }

    return 0;
}
Beispiel #15
0
void run(Factory *f) {
    ontology::Ontology ontology(f, verbose);

    // Starting code Generation
    std::set<std::string> cppNameSpaces;

    for ( auto const& klassMapItem: ontology.classUri2Ptr()) {
        // created directory if needed
        createDirectory(Klass(*klassMapItem.second).genCppNameSpaceInclusionPath());
        cppNameSpaces.insert(Klass(*klassMapItem.second).genCppNameSpace());

        Klass(*klassMapItem.second).generateInterfaceDeclaration();
        Klass(*klassMapItem.second).generateInterfaceDefinition();
        Klass(*klassMapItem.second).generateDeclaration();
        Klass(*klassMapItem.second).generateDefinition();
    }

    // Generate all TypesInfo
    generateRdfTypeInfo(ontology);

    // Generate all inclusions files
    for ( const std::string& cppNameSpace : cppNameSpaces ) {
        std::ofstream ofs;
        createFile(Klass::outdir + "/" + cppNameSpace + "/" + cppNameSpace + ".h", &ofs);

        generateCodeProtectorBegin(ofs, cppNameSpace, cppNameSpace);
        for ( auto const& klassMapItem: ontology.classUri2Ptr()) {
            if ( Klass(*klassMapItem.second).genCppNameSpace() == cppNameSpace ) {
                const Klass& cls = *klassMapItem.second;
                ofs << "#include <" << cls.genCppNameSpaceInclusionPath() << "/" << klassMapItem.second->prettyIRIName() << ".h" << ">" << std::endl;
            }
        }
        ofs << std::endl;
        generateCodeProtectorEnd(ofs, cppNameSpace, cppNameSpace);
    }

    // Generate all in one cpp file
    if ( generateAllInOne ) {
        std::ofstream ofs;
        createFile(RdfsEntity::outdir + "/AllInOne.cpp", &ofs);

        addBoilerPlate(ofs);
        ofs << std::endl;
        ofs << "#include \"RdfTypeInfo.cpp\"" << std::endl;
        for ( auto const& klassMapItem: ontology.classUri2Ptr()) {
            const Klass& cls = *klassMapItem.second;
            ofs << "#include \"" << cls.genCppNameSpaceInclusionPath() << "/I" << klassMapItem.second->prettyIRIName() << ".cpp" << "\"" << std::endl;
            ofs << "#include \"" << cls.genCppNameSpaceInclusionPath() << "/" << klassMapItem.second->prettyIRIName() << ".cpp" << "\"" << std::endl;
        }
        ofs << std::endl;
    }
}
Beispiel #16
0
bool
createParentDirectories(const std::string &path)
{
   auto slashPos = path.find_last_of("/\\");

   if (slashPos == std::string::npos
       || (slashPos == 2 && isDriveName(path.substr(0, 2)))
       || (path.find_first_not_of("/\\") == 2  // "\\server\path" syntax
           && path.find_first_of("/\\", 2) == slashPos)) {
      return true;
   }

   return createDirectory(path.substr(0, slashPos));
}
Beispiel #17
0
void TextOutput::commit(bool flush) {
    std::string p = filenamePath(filename);
    if (! fileExists(p, false)) {
        createDirectory(p);
    }

    FILE* f = fopen(filename.c_str(), "wb");
    debugAssertM(f, "Could not open \"" + filename + "\"");
    fwrite(data.getCArray(), 1, data.size(), f);
    if (flush) {
        fflush(f);
    }
    fclose(f);
}
Beispiel #18
0
//-----------------------------------------------------------------------------
StatusCode RootHistCnv::RDirectoryCnv::createRep(DataObject* pObject,
                                                 IOpaqueAddress*& refpAddress)
//-----------------------------------------------------------------------------
{
  const std::string& loc = pObject->registry()->identifier();
  if ( createDirectory(loc).isSuccess() )   {
    setDirectory(loc);
    setDiskDirectory(loc);
//  return createAddress(pObject, pObject->registry()->name(), refpAddress);
    return createAddress(pObject, gDirectory, 0, refpAddress);
  }
  refpAddress = 0;
  return StatusCode::FAILURE;
}
Beispiel #19
0
int main(int argc, const char * argv[])
{
	/*
	 * Actual app
	 */
	// Setup Connection to DB
	setupConnection();
	
	// Create dirs
	createDirectory(BackgroundDIR);
	createDirectory(TargetDIR);
	
	// Run Menu
	menuSelect();
	
	// Close Connection
	closeConnection();
	/*
	 * END Actual app
	 */
	
    return 0;
}
Beispiel #20
0
bool UpdateManager::createDirForFile(string str)
{
	int worklength=resourcesPath.length()+1;
	for(int i=worklength;i<(int)(str.length());++i)
	{
		if(str[i]=='/')
		{
			string sub=str.substr(0,i);
			createDirectory(sub.c_str());
		}
	}
	return true;

}
Beispiel #21
0
Result ZipFile::uncompressEntry (int index, const File& targetDirectory, bool shouldOverwriteFiles)
{
    auto* zei = entries.getUnchecked (index);

   #if JUCE_WINDOWS
    auto entryPath = zei->entry.filename;
   #else
    auto entryPath = zei->entry.filename.replaceCharacter ('\\', '/');
   #endif

    if (entryPath.isEmpty())
        return Result::ok();

    auto targetFile = targetDirectory.getChildFile (entryPath);

    if (entryPath.endsWithChar ('/') || entryPath.endsWithChar ('\\'))
        return targetFile.createDirectory(); // (entry is a directory, not a file)

    ScopedPointer<InputStream> in (createStreamForEntry (index));

    if (in == nullptr)
        return Result::fail ("Failed to open the zip file for reading");

    if (targetFile.exists())
    {
        if (! shouldOverwriteFiles)
            return Result::ok();

        if (! targetFile.deleteFile())
            return Result::fail ("Failed to write to target file: " + targetFile.getFullPathName());
    }

    if (! targetFile.getParentDirectory().createDirectory())
        return Result::fail ("Failed to create target folder: " + targetFile.getParentDirectory().getFullPathName());

    {
        FileOutputStream out (targetFile);

        if (out.failedToOpen())
            return Result::fail ("Failed to write to target file: " + targetFile.getFullPathName());

        out << *in;
    }

    targetFile.setCreationTime (zei->entry.fileTime);
    targetFile.setLastModificationTime (zei->entry.fileTime);
    targetFile.setLastAccessTime (zei->entry.fileTime);

    return Result::ok();
}
Beispiel #22
0
void copySysOSX(const char* projName)
{
#ifdef _DEBUG
	const char * appName = "MaratisPlayerDebug";
#else
	const char * appName = "MaratisPlayer";
#endif

	MWindow * window = MWindow::getInstance();
	MEngine* engine = MEngine::getInstance();
	MSystemContext* system = engine->getSystemContext();

	char filename[256];
	getLocalFilename(filename, system->getWorkingDirectory(), projName);

	if(char* ext = strstr(filename, ".mproj"))
	{
		MProject proj;
		if(proj.loadXML(projName))
		{
			strcpy(ext, ".app");

			char path[256];
			char srcName[256];
			char destName[256];
			char appPath[256];
			char level[256];

			getLocalFilename(level, system->getWorkingDirectory(), proj.startLevel.c_str());
			getGlobalFilename(appPath, getPubDir(), filename);

			sprintf(path, "../../../%s.app", appName);
			getGlobalFilename(srcName, window->getCurrentDirectory(), path);
			copyDirectory(srcName, appPath);

			strcpy(ext, "");
			sprintf(srcName, "%s/Contents/MacOS/%s", appPath, appName);

			strcpy(ext, ".mproj");
			embedProject(srcName, srcName, filename, level, proj.renderer.c_str());
			chmod(srcName, 0777);

			// we need to put all data in app/Contents/Resources/
			sprintf(destName, "%s/Contents/Resources", appPath);
			createDirectory(destName);
			s_dataDir = destName;
		}
	}
}
MainWindow::MainWindow(QWidget *parent) :
	QMainWindow(parent),
	_ui(new Ui::MainWindow),
	_clipboard(QApplication::clipboard()),
	_proxyModel(new QSortFilterProxyModel),
	_storageModel(),
	_objectModel(new MtpObjectsModel()),
	_uploader(new FileUploader(_objectModel, this))
{
	_ui->setupUi(this);
	setWindowIcon(QIcon(":/android-file-transfer.png"));

	_ui->listView->setModel(_proxyModel);

	_proxyModel->setSortCaseSensitivity(Qt::CaseInsensitive);
	_proxyModel->sort(0);
	_proxyModel->setDynamicSortFilter(true);

	_objectModel->moveToThread(QApplication::instance()->thread());

	connect(_ui->listView->selectionModel(), SIGNAL(selectionChanged(const QItemSelection &, const QItemSelection &)), SLOT(updateActionsState()));
	connect(_ui->listView, SIGNAL(doubleClicked(QModelIndex)), SLOT(onActivated(QModelIndex)));
	connect(_ui->listView, SIGNAL(customContextMenuRequested(QPoint)), SLOT(showContextMenu(QPoint)));
	connect(_ui->actionBack, SIGNAL(triggered()), SLOT(back()));
	connect(_ui->actionGo_Down, SIGNAL(triggered()), SLOT(down()));
	connect(_ui->actionCreateDirectory, SIGNAL(triggered()), SLOT(createDirectory()));
	connect(_ui->actionUploadDirectory, SIGNAL(triggered()), SLOT(uploadDirectories()));
	connect(_ui->actionUpload_Album, SIGNAL(triggered()), SLOT(uploadAlbum()));
	connect(_ui->actionUpload, SIGNAL(triggered()), SLOT(uploadFiles()));
	connect(_ui->actionRename, SIGNAL(triggered()), SLOT(renameFile()));
	connect(_ui->actionDownload, SIGNAL(triggered()), SLOT(downloadFiles()));
	connect(_ui->actionDelete, SIGNAL(triggered()), SLOT(deleteFiles()));
	connect(_ui->storageList, SIGNAL(activated(int)), SLOT(onStorageChanged(int)));
	connect(_ui->actionRefresh, SIGNAL(triggered()), SLOT(refresh()));
	connect(_ui->actionPaste, SIGNAL(triggered()), SLOT(pasteFromClipboard()));

	connect(_objectModel, SIGNAL(onFilesDropped(QStringList)), SLOT(uploadFiles(QStringList)));
	connect(_objectModel, SIGNAL(existingFileOverwrite(QString)), SLOT(confirmOverwrite(QString)), Qt::BlockingQueuedConnection);

	connect(_clipboard, SIGNAL(dataChanged()), SLOT(validateClipboard()));
	validateClipboard();

	//fixme: find out how to specify alternative in designer
	_ui->actionBack->setShortcuts(_ui->actionBack->shortcuts() << QKeySequence("Alt+Up") << QKeySequence("Esc"));
	_ui->actionGo_Down->setShortcuts(_ui->actionGo_Down->shortcuts() << QKeySequence("Alt+Down") << QKeySequence("Enter"));
	_ui->actionCreateDirectory->setShortcuts(_ui->actionCreateDirectory->shortcuts() << QKeySequence("F7"));
	_ui->actionRefresh->setShortcuts(_ui->actionRefresh->shortcuts() << QKeySequence("Ctrl+R"));
	_ui->listView->setFocus();
}
Beispiel #24
0
void takeScreenShot(const string prefix) {
	ILuint handle=0;
	ilGenImages(1, &handle);
	
	ilBindImage(handle);
	ilutGLScreen();
	
	createDirectory(FileName("sshots/"));
	
	char *pszScreenShotFileName = strdup(getScreenShotFileName(prefix).str());
	ilSaveImage(pszScreenShotFileName);
	delete[] pszScreenShotFileName;
	
	ilDeleteImages(1, &handle);
}
	void setupDirectoryIndexes(){
		if(existsFile(getDataDirectory())){
			if(isInfoEnabled()) info(concatAll( 3, "Usando " , getDataDirectory() , " como directorio de indices"));
		}else{
			if(isInfoEnabled()) info(concatAll(2 , "No existe el directorio " , getDataDirectory()));

			if(createDirectory(getDataDirectory())){
				if(isInfoEnabled()) info(concatAll(2 , "Se crea " , getDataDirectory()));
			}else{
				if(isInfoEnabled()) info(concatAll(2 , "No se pudo crear el directorio " , getDataDirectory()));
				killAndWait(1);
				return;
			}
		}
	}
Beispiel #26
0
bool SDCardClass::writeFile(const char *path, const uint8_t *buf, uint8_t len, bool createDir) {
  SDCardFile file(path);
  SDCardEntry parentDir(file.dir);
  if (!parentDir.exists) {
    if (createDir) {
      if (!createDirectory(file.dir)) {
	return false;
      }
      parentDir.setPath(file.dir);
    } else {
      return false;
    }
  }

  return (file.writeFile(buf, len) == len);
}
Beispiel #27
0
void copyFile( const char* szSrc, 
			   const char* szDestDirectory )
{
    
	createDirectory( szDestDirectory );
    
    FILE* pSrc = fopen( szSrc, "rb" );
	WTFASSERT2( pSrc, "can't open %s", szSrc );

	char szFileName[256];
	getFileName( szFileName, szSrc, sizeof( szFileName ) );

	char szDest[512];
	memset( szDest, 0, sizeof( szDest ) );
	snprintf( szDest, sizeof( szDest ), "%s/%s", szDestDirectory, szFileName );

	FILE* pDest = fopen( szDest, "wb" );
	WTFASSERT2( pDest, "can't save to %s", szDest );

	int iTempSize = ( 1 << 16 );
	char* aTempBuffer = (char *)MALLOC( iTempSize );
	
	fseek( pSrc, 0, SEEK_END );
	long iFileSize = ftell( pSrc );
	fseek( pSrc, 0, SEEK_SET );

	// copy chunks of memory
	int iNumChunks = (int)( iFileSize / (long)iTempSize );
	int iLeftOver = ( iFileSize % iTempSize );
	for( int i = 0; i < iNumChunks; i++ )
	{
		fread( aTempBuffer, sizeof( char ), iTempSize, pSrc );
		fwrite( aTempBuffer, sizeof( char ), iTempSize, pDest );
		fseek( pDest, 0, SEEK_END );
	}

	if( iLeftOver > 0 )
	{
		fread( aTempBuffer, sizeof( char ), iLeftOver, pSrc );
		fwrite( aTempBuffer, sizeof( char ), iLeftOver, pDest );
	}

	FREE( aTempBuffer );

	fclose( pSrc );
	fclose( pDest );
}
Beispiel #28
0
void Invocation::createEnvironment() {
	string tmp = params->getProgramFileName();
	if (tmp.rfind(".exe") != tmp.length() - 4) error("Only executable files are accepted to testing");
	if (!createDirectory(params->getInvocationDirectory())) error("Cannot create temporary directory for testing environment");
	environmentCreated = true;
	if (!copyFile(tmp, params->getProgramPath())) error("Cannot copy program file to working directory");
	tmp = params->getCheckerFileName();
	if (!tmp.find("std::")) {
		for (int i = 0; i < STD_CHECKERS_COUNT; ++i)
			if (STD_CHECKERS_NAME[i] == tmp) {
				getFileFromResource(STD_CHECKERS_RESOURCE_CODE[i], params->getCheckerPath());
				return;
			}
		error("Unknown standart checker \"" + tmp + "\" is set");
	} else 
	if (tmp.rfind(".exe") != tmp.length() - 4) error("Checkers must be executable files"); else
	if (!copyFile(tmp, params->getCheckerPath())) error("Cannot copy checker file to working directory");
}
Beispiel #29
0
Viewer::Settings::Settings(const std::string& applicationName, const FilePath& filepath):
    m_FilePath(filepath) {

    if(tinyxml2::XML_NO_ERROR != m_Document.LoadFile(filepath.c_str())) {
        throw std::runtime_error("Unable to load viewer settings file");
    }

    if(nullptr == (m_pRoot = m_Document.RootElement())) {
        throw std::runtime_error("Invalid viewer settings file format (no root element)");
    }

    auto pWindow = m_pRoot->FirstChildElement("Window");
    if(!pWindow) {
        throw std::runtime_error("Invalid viewer settings file format (no Window element)");
    }

    if(!getAttribute(*pWindow, "width", m_WindowSize.x) ||
            !getAttribute(*pWindow, "height", m_WindowSize.y)) {
        throw std::runtime_error("Invalid viewer settings file format (no width/height params)");
    }

    auto pViewController = m_pRoot->FirstChildElement("ViewController");
    if(pViewController) {
        if(!getAttribute(*pViewController, "speedFarRatio", m_fSpeedFarRatio)) {
            throw std::runtime_error("Invalid viewer settings file format (no speedFarRatio params in ViewController)");
        }
    }

    auto pFramebuffer = m_pRoot->FirstChildElement("Framebuffer");
    if(!getAttribute(*pFramebuffer, "width", m_FramebufferSize.x) ||
            !getAttribute(*pFramebuffer, "height", m_FramebufferSize.y)) {
        throw std::runtime_error("Invalid viewer settings file format (no width/height params for the framebuffer)");
    }
    m_fFramebufferRatio = float(m_FramebufferSize.x) / m_FramebufferSize.y;

    auto cacheDirectory = filepath.directory() + "cache";
    createDirectory(cacheDirectory);
    m_CacheFilePath = cacheDirectory + (applicationName + ".cache.bnz.xml");
    if(tinyxml2::XML_NO_ERROR != m_CacheDocument.LoadFile(m_CacheFilePath.c_str())) {
        auto pRoot = m_CacheDocument.NewElement("Cache");
        m_CacheDocument.InsertFirstChild(pRoot);
    }
    m_pCacheRoot = m_CacheDocument.RootElement();
}
Beispiel #30
0
/*
 * Class:     edu_uw_apl_commons_tsk4j_filesys_FileSystem
 * Method:    dirOpenMeta
 * Signature: (JJ)Ledu/uw/apl/commons/tsk4j/filesys/Directory;
 */
JNIEXPORT jobject JNICALL 
Java_edu_uw_apl_commons_tsk4j_filesys_FileSystem_dirOpenMeta
(JNIEnv *env, jobject thiz, jlong nativePtr, jlong metadataAddr ) {

  TSK_FS_INFO* info = (TSK_FS_INFO*)nativePtr;
  TSK_FS_DIR* fsDir = tsk_fs_dir_open_meta( info, (TSK_INUM_T)metadataAddr );
  if( fsDir == NULL )
	return (jobject)NULL;
  TSK_FS_FILE* fsFile = fsDir->fs_file;

  jobject fileMeta = NULL;
  if( fsFile->meta ) {
	fileMeta = createFileMeta( env, fsFile->meta );
	if( !fileMeta ) {
	  tsk_fs_dir_close( fsDir );
	  return NULL;
	}
  }

  jobject fileName = NULL;
  if( fsFile->name ) {
	fileName = createFileName( env, fsFile->name );
	if( !fileName ) {
	  tsk_fs_dir_close( fsDir );
	  // LOOK: release fileMeta ????
	  return NULL;
	}
  }

  jobject file = createFile( env, fsFile, thiz, fileMeta, fileName ); 
  if( !file ) {
	  tsk_fs_dir_close( fsDir );
	  // LOOK: release fileMeta, fileName ????
	  return NULL;
  }
  
  jobject result = createDirectory( env, fsDir, thiz, file );
  if( !result ) {
	  tsk_fs_dir_close( fsDir );
	  // LOOK: release fileMeta, fileName, file ????
	  return NULL;
  }
  return result;
}