void VTKMoleculeWriterImplementationTest::testWriteVTKFile() { #ifdef ENABLE_MPI int rank = 0; MPI_Comm_rank(MPI_COMM_WORLD, &rank); if (rank != 0) { return; } #endif VTKMoleculeWriterImplementation writer(0); std::vector<Component> components; Component dummyComponent(0); dummyComponent.addLJcenter(0,0,0,0,0,0,0,false); components.push_back(dummyComponent); Molecule dummyMolecule(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, &components); std::vector<std::string> v; writer.initializeVTKFile(); writer.initializeParallelVTKFile(v); writer.plotMolecule(dummyMolecule); writer.plotMolecule(dummyMolecule); ASSERT_EQUAL(writer.getNumMoleculesPlotted(), 2u); writer.writeVTKFile("VTKMoleculeWriter00.vtu"); ASSERT_TRUE(fileExists("VTKMoleculeWriter00.vtu")); writer.writeParallelVTKFile("VTKMoleculeWriter00.pvtu"); ASSERT_TRUE(fileExists("VTKMoleculeWriter00.pvtu")); removeFile("VTKMoleculeWriter00.vtu"); removeFile("VTKMoleculeWriter00.pvtu"); }
bool BcmWarmBootHelper::checkAndClearWarmBootFlags() { // Return true if coldBootOnceFile does not exist and // canWarmBoot file exists bool canWarmBoot = removeFile(warmBootFlag()); bool forceColdBoot = removeFile(forceColdBootOnceFlag()); return !forceColdBoot && canWarmBoot; }
void SourceFileModel::removeFiles(QList<SourceFile *> const &files) { auto filesToRemove = files.toSet(); auto tracksToRemove = QSet<Track *>{}; for (auto const &file : files) { for (auto const &track : file->m_tracks) tracksToRemove << track.get(); for (auto const &appendedFile : file->m_appendedFiles) { filesToRemove << appendedFile.get(); for (auto const &track : appendedFile->m_tracks) tracksToRemove << track.get(); } } m_tracksModel->reDistributeAppendedTracksForFileRemoval(filesToRemove); m_tracksModel->removeTracks(tracksToRemove); auto filesToRemoveLast = QList<SourceFile *>{}; for (auto &file : filesToRemove) if (!file->isRegular()) removeFile(file); else filesToRemoveLast << file; for (auto &file : filesToRemoveLast) if (file->isRegular()) removeFile(file); }
TEST_F(getLinkCountTest, LinkCountOfMultiplyLinkedFile) { createFileForTesting(file); std::string newFile = createHardLink(file); int32_t ret = GetLinkCount(file, &count); ASSERT_EQ(0, ret); EXPECT_EQ(2, count); removeFile(file); removeFile(newFile); }
void removeAllInFolder(HFSCatalogNodeID folderID, Volume* volume, const char* parentName) { CatalogRecordList* list; CatalogRecordList* theList; char fullName[1024]; char* name; char* pathComponent; int pathLen; char isRoot; HFSPlusCatalogFolder* folder; theList = list = getFolderContents(folderID, volume); strcpy(fullName, parentName); pathComponent = fullName + strlen(fullName); isRoot = FALSE; if(strcmp(fullName, "/") == 0) { isRoot = TRUE; } while(list != NULL) { name = unicodeToAscii(&list->name); if(isRoot && (name[0] == '\0' || strncmp(name, ".HFS+ Private Directory Data", sizeof(".HFS+ Private Directory Data") - 1) == 0)) { free(name); list = list->next; continue; } strcpy(pathComponent, name); pathLen = strlen(fullName); if(list->record->recordType == kHFSPlusFolderRecord) { folder = (HFSPlusCatalogFolder*)list->record; fullName[pathLen] = '/'; fullName[pathLen + 1] = '\0'; removeAllInFolder(folder->folderID, volume, fullName); } else { printf("%s\n", fullName); removeFile(fullName, volume); } free(name); list = list->next; } releaseCatalogRecordList(theList); if(!isRoot) { *(pathComponent - 1) = '\0'; printf("%s\n", fullName); removeFile(fullName, volume); } }
/**OK * Estrae il file fileName, contenuto nell'oggetto zip, con il nome fileDest. * Se la funzione fallisce restituisce false e cancella il file che si e tentato di estrarre. * * La funzione fallisce se: * * zip==NULL; * * l'oggetto zip e stato aperto in una modalita non compatibile con l'estrazione di file; * * non e possibile aprire il file all'interno dell'oggetto zip; * * non e possibile creare il file estratto; * * si e rilevato un errore nella copia dei dati (1); * * non e stato possibile chiudere il file all'interno dell'oggetto zip (1); * * (1): prima di uscire dalla funzione cancella il file estratto. */ bool JlCompress::extractFile(QuaZip* zip, QString fileName, QString fileDest) { // zip: oggetto dove aggiungere il file // filename: nome del file reale // fileincompress: nome del file all'interno del file compresso // Controllo l'apertura dello zip if (!zip) return false; if (zip->getMode()!=QuaZip::mdUnzip) return false; // Apro il file compresso if (!fileName.isEmpty()) zip->setCurrentFile(fileName); QuaZipFile inFile(zip); if(!inFile.open(QIODevice::ReadOnly) || inFile.getZipError()!=UNZ_OK) return false; // Controllo esistenza cartella file risultato QDir curDir; if (!curDir.mkpath(QFileInfo(fileDest).absolutePath())) { return false; } QuaZipFileInfo info; if (!zip->getCurrentFileInfo(&info)) return false; if (fileDest.endsWith('/') && QFileInfo(fileDest).isDir()) { return QFile(fileDest).setPermissions(info.getPermissions()); } // Apro il file risultato QFile outFile; outFile.setFileName(fileDest); if(!outFile.open(QIODevice::WriteOnly)) return false; // Copio i dati if (!copyData(inFile, outFile) || inFile.getZipError()!=UNZ_OK) { outFile.close(); removeFile(QStringList(fileDest)); return false; } outFile.close(); // Chiudo i file inFile.close(); if (inFile.getZipError()!=UNZ_OK) { removeFile(QStringList(fileDest)); return false; } return outFile.setPermissions(info.getPermissions()); }
/* * FUNCTION: Merge Two IndexInfo * INPUT: IndexInfo & RequestInfo * OUTPUT: IndexInfo * (SIDE)EFFECTS: Merge Two IndexInfo */ IndexInfo merge(list<IndexInfo> *indexList, IndexInfo oldIndex, RequestInfo request) { int * mapxy = mapXY(request.startx, request.starty, request.endx, request.endy); int newStartx = oldIndex.startx<mapxy[0] ? oldIndex.startx : mapxy[0]; int newStarty = oldIndex.starty<mapxy[1] ? oldIndex.starty : mapxy[1]; int newEndx = oldIndex.endx>mapxy[2] ? oldIndex.endx : mapxy[2]; int newEndy = oldIndex.endy>mapxy[3] ? oldIndex.endy : mapxy[3]; double newSize = 0; IndexInfo newIndex = {request.fileName, newStartx, newStarty, newEndx, newEndy, oldIndex.count, request.genTime, newSize, oldIndex.priority}; list<IndexInfo>::iterator iter; for(iter=(*indexList).begin(); iter!=(*indexList).end(); iter++){ if(!((*iter).fileName).compare(oldIndex.fileName)){ iter = (*indexList).erase(iter); //remove old removeFile(oldIndex.fileName); } } return newIndex; }
void Filemanager::filesDelete() { // getting the selected items QModelIndexList selectedItems = m_files->selectionModel()->selectedIndexes(); // removing each item from File System for( QModelIndexList::iterator item = selectedItems.begin(); item != selectedItems.end(); ++item ) { QString itemDisplayName = m_filesModel->data(*item,Qt::DisplayRole).toString(); if( (itemDisplayName == "..") || (itemDisplayName == ".") ) continue; QString itemName = m_filesModel->data(*item,Qt::StatusTipRole).toString(); if( QFileInfo(itemName).isFile() ) { if( false == removeFile(itemName) ) BaloonNotificationManager::showBaloonNotification(QString(ERROR_ON_FILE_REMOVE).arg(itemName)); } else { if( false == removeFolder(itemName) ) BaloonNotificationManager::showBaloonNotification(QString(ERROR_ON_FOLDER_REMOVE).arg(itemName)); } } // refreshing the content for current folder refreshCurrentFolder(); }
/** Removes a directory (including all files contained). The function could * easily recursively delete further subdirectories, but this is commented * out atm (to limit the amount of damage in case of a bug). * \param name Directory name to remove. * \param return True if removal was successful. */ bool FileManager::removeDirectory(const std::string &name) const { std::set<std::string> files; listFiles(files, name, /*is full path*/ true); for(std::set<std::string>::iterator i=files.begin(); i!=files.end(); i++) { if((*i)=="." || (*i)=="..") continue; if(UserConfigParams::logMisc()) Log::verbose("FileManager", "Deleting directory '%s'.", (*i).c_str()); if(isDirectory(*i)) { // This should not be necessary (since this function is only // used to remove addons), and it limits the damage in case // of any bugs - i.e. if name should be "/" or so. // removeDirectory(full_path); } else { removeFile(*i); } } #if defined(WIN32) return RemoveDirectory(name.c_str())==TRUE; #else return remove(name.c_str())==0; #endif } // remove directory
/** Redirects output to go into files in the user's config directory * instead of to the console. It keeps backup copies of previous stdout files * (3 atm), which can help to diagnose problems caused by a previous crash. */ void FileManager::redirectOutput() { // Do a simple log rotate: stdout.log.2 becomes stdout.log.3 etc const int NUM_BACKUPS=3; std::string logoutfile = getUserConfigFile("stdout.log"); for(int i=NUM_BACKUPS; i>1; i--) { std::ostringstream out_old; out_old << logoutfile << "." << i; removeFile(out_old.str()); std::ostringstream out_new; out_new << logoutfile << "." << i-1; if(fileExists(out_new.str())) { rename(out_new.str().c_str(), out_old.str().c_str()); } } // for i in NUM_BACKUPS if(fileExists(logoutfile)) { std::ostringstream out; out << logoutfile<<".1"; // No good place to log error messages when log is not yet initialised rename(logoutfile.c_str(), out.str().c_str()); } //Enable logging of stdout and stderr to logfile Log::verbose("main", "Error messages and other text output will " "be logged to %s.", logoutfile.c_str()); Log::openOutputFiles(logoutfile); } // redirectOutput
bool XMLParser::removeChild(std::string filename, std::string value) const { std::string path; path = PATH; path += filename; std::ofstream outFile("../XML_file/temp.xml"); std::fstream readFile(path.c_str(), std::fstream::in); std::string line; if (outFile.fail()) { print_error(" Ouverture temp.xml "); return (false); } if (readFile.fail()) { print_error(" Lecture temp.xml "); return (false); } while (std::getline(readFile, line)) { if (line.find("<id>" + value + "</id>") == std::string::npos) outFile << line << std::endl; } readFile.close(); outFile.close(); removeFile(path); renameFile("../XML_file/temp.xml", path); return (true); }
void FileEditionWidget::setFiles(const QStringList &filenames) { ui->tableWidget->clear(); ui->tableWidget->setColumnCount(2); ui->tableWidget->setRowCount(filenames.count()); ui->tableWidget->horizontalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents); ui->tableWidget->horizontalHeader()->setSectionResizeMode(FilenamePos, QHeaderView::Stretch); int row = 0; foreach(const QString& file, filenames) { QTableWidgetItem* item = new QTableWidgetItem(file); ui->tableWidget->setItem(row, FilenamePos, item); ButtonWidget* btns = new ButtonWidget(this); ui->tableWidget->setCellWidget(row, ButtonsPos, btns); _editMapper->setMapping(btns, file); _exportMapper->setMapping(btns, file); _importMapper->setMapping(btns, file); _resetMapper->setMapping(btns, file); connect(btns, SIGNAL(editFile()), _editMapper, SLOT(map())); connect(btns, SIGNAL(exportFile()), _exportMapper, SLOT(map())); connect(btns, SIGNAL(importFile()), _importMapper, SLOT(map())); connect(btns, SIGNAL(removeFile()), _resetMapper, SLOT(map())); ++row; }
int closeFile(int keep) { int i; char *back; if (!fileOpen()) { fprintf(stderr, "No open file to close.\n"); return FAIL; } /* free some dynamic storages */ if (he_backup && !keep) { back = backupName(he_file); (void) removeFile(back); HDfree(back); } HDfree(he_file); he_file = NULL; for (i = 0; i < he_numGrp; i++) HDfree(he_grp[i].ddList); return HE_OK; }
TEST(Stream, append) { const std::wstring LOG_FILE_NAME(L"StreamTest.log"); removeFile(LOG_FILE_NAME); auto output(std::make_unique<LogOutput>(LOG_FILE_NAME)); auto prefix(std::make_unique<NothingPrefix>()); unsigned char uc[] = "uc"; void* pointer = reinterpret_cast<void*>(12345678U); LogStream logStream(std::move(output), std::move(prefix)); logStream << bkzFlush; logStream << 1; logStream << 2U; logStream << 1L; logStream << 2LU; logStream << 4.4f; logStream << 3.3; logStream << "HELLO"; logStream << uc; logStream << std::string("string"); logStream << std::wstring(L"wstring"); logStream << pointer; logStream << bkzEndl; const std::wstring actual = stringFromFile(LOG_FILE_NAME); EXPECT_EQ(L"12124.403.300HELLOucstringwstring12345678\n", actual); }
void RollingFileAppender::rollOver() { // Q_ASSERT_X(, "RollingFileAppender::rollOver()", "Lock must be held by caller") logger()->debug("Rolling over with maxBackupIndex = %1", mMaxBackupIndex); closeFile(); QFile f; f.setFileName(file() + QLatin1Char('.') + QString::number(mMaxBackupIndex)); if (f.exists() && !removeFile(f)) return; QString target_file_name; int i; for (i = mMaxBackupIndex - 1; i >=1; i--) { f.setFileName(file() + QLatin1Char('.') + QString::number(i)); if (f.exists()) { target_file_name = file() + QLatin1Char('.') + QString::number(i + 1); if (!renameFile(f, target_file_name)) return; } } f.setFileName(file()); target_file_name = file() + QLatin1String(".1"); if (!renameFile(f, target_file_name)) return; openFile(); }
void RecentBooksDlg::on_actionRemoveBook_triggered() { int cr = m_ui->tableWidget->currentRow(); if(cr<0) cr=0; int firstItem = m_docview->getDocView()->isDocumentOpened() ? 1 : 0; LVPtrVector<CRFileHistRecord> & files = m_docview->getDocView()->getHistory()->getRecords(); int row = getBookNum() + firstItem; if(row>files.length()) return; removeFile(files, row); SetPageCount(); if(curPage>pageCount) curPage-=1; curPage-=1; // select row cr = (row-firstItem)*2-1; if((cr+firstItem)/2 >= files.length()) cr = files.length()*2-3; if(cr<0) cr=1; ShowPage(1, cr); }
void RecentlyOpenedFilesList::addFile (const File& file) { removeFile (file); files.insert (0, file.getFullPathName()); setMaxNumberOfItems (maxNumberOfItems); }
/* Reply from the server after a check in. With this lua code insertion (and proper security), we can do several things, including event notification, forum news/update/private message notification, random item drops, additional data requests, etc. */ void dlCallback_CheckInSuccess(downloadData* data) { if (game->mMap && game->mMap->mLuaState) mapLib_CallCheckin(game->mMap->mLuaState, data->filename); removeFile(data->filename); }
int main(int argc, char **argv) { char *sosuFile = makeTempFile("sosu"); uint64 value; uint64 max = toValue64(nextArg()); errorCase(max < 11); errorCase(max == UINT64MAX); SosuFp = fileOpen(sosuFile, "a+b"); SosuCnt = 0; for(value = 11; value <= max; value += 2) { if((value & 0x3ffe) == 0) cmdTitle_x(xcout("Prime2tox - %I64u", value)); if( value % 3 != 0 && value % 5 != 0 && value % 7 != 0 && IsSosu(value) ) AddSosu(value); } cmdTitle("Prime2tox - Completed"); DispSosu(); fileClose(SosuFp); removeFile(sosuFile); memFree(sosuFile); }
bool Fifo::tryConnect() noexcept { if (isConnected()) { return true; } if (!exists(path_.c_str())) { if (!create(path_.c_str())) { static bool logged{false}; if (!logged) { VLOG(1) << "Error creating debug fifo at \"" << path_ << "\": " << strerror(errno) << " [" << errno << "]"; logged = true; } return false; } } if (!isFifo(path_.c_str()) || !canWrite(path_.c_str())) { if (!removeFile(path_.c_str()) || !create(path_.c_str())) { return false; } } int fd = folly::openNoInt(path_.c_str(), O_WRONLY | O_NONBLOCK); if (fd >= 0) { fd_.store(fd); return true; } return false; }
void QgsMSLayerCache::freeEntryResources( QgsMSLayerCacheEntry& entry ) { // remove layer from QgsProject before delete it if ( QgsProject::instance()->mapLayer( entry.layerPointer->id() ) ) QgsProject::instance()->removeMapLayer( entry.layerPointer->id() ); delete entry.layerPointer; //remove the temporary files of a layer Q_FOREACH ( const QString& file, entry.temporaryFiles ) { //remove the temporary file QFile removeFile( file ); if ( !removeFile.remove() ) { QgsDebugMsg( "could not remove file: " + file ); QgsDebugMsg( removeFile.errorString() ); } } //counter if ( !entry.configFile.isEmpty() ) { int configFileCount = mConfigFiles[entry.configFile]; if ( configFileCount < 2 ) { mConfigFiles.remove( entry.configFile ); mFileSystemWatcher.removePath( entry.configFile ); } else { mConfigFiles[entry.configFile] = configFileCount - 1; } } }
void BCLXML::addFile(const BCLFileReference& file) { removeFile(file.path()); incrementVersionId(); m_files.push_back(file); }
QFakeMail::QFakeMail() : QMainWindow(0), email("([a-z0-9._%+-]+@[a-z0-9-]+\\.[a-z0-9.-]+)", Qt::CaseInsensitive) { setupUi(this); connect(server, SIGNAL(textEdited(const QString&)), SLOT(change())); connect(isfrom, SIGNAL(toggled(bool)), SLOT(change())); connect(from, SIGNAL(textEdited(const QString&)), SLOT(change())); connect(to, SIGNAL(textEdited(const QString&)), SLOT(change())); connect(files, SIGNAL(itemSelectionChanged()), SLOT(filesSelected())); connect(removefile, SIGNAL(clicked()), SLOT(removeFile())); connect(addfile, SIGNAL(clicked()), SLOT(addFile())); connect(send, SIGNAL(clicked()), SLOT(sendSlot())); connect(actionAbout, SIGNAL(triggered()), SLOT(about())); connect(&sock, SIGNAL(error(QAbstractSocket::SocketError)), SLOT(gotErrorSlot())); connect(&sock, SIGNAL(disconnected()), SLOT(disconnected())); connect(&sock, SIGNAL(connected()), SLOT(connected())); connect(&sock, SIGNAL(readyRead()), SLOT(readed())); QSettings settings; int size = settings.beginReadArray("recents"); for (int i = 0; i < size; i++) { settings.setArrayIndex(i); recents << settings.value("server").toString(); } settings.endArray(); server->setCompleter(new QCompleter(recents, server)); }
void ViewFileManager::on(QueueManagerListener::ItemRemoved, const QueueItemPtr& aQI, bool finished) noexcept { if (finished || !isViewedItem(aQI)) { return; } removeFile(aQI->getTTH()); }
void cmd_rm(Volume* volume, int argc, const char *argv[]) { if(argc > 1) { removeFile(argv[1], volume); } else { printf("Not enough arguments"); } }
bool MpkManip::removeDir(const char* dir) { bool bOk = true; std::string strDir = dir; if(!strDir.empty()) strDir = strDir + "\\*"; else strDir = "*"; SFILE_FIND_DATA fileFindData; HANDLE hFind = SFileFindFirstFile(m_hMpk,strDir.c_str(),&fileFindData,0); if(hFind) { do { if(!removeFile(fileFindData.cFileName)) { bOk = false; } } while(SFileFindNextFile(hFind,&fileFindData)); SFileFindClose(hFind); } return bOk; }
void BufferManager::dropBuffer(Buffer* buffer) { if (_log->isDebug()) _log->debug(2, "dropBuffer(buffer: fileName %s)", buffer->fileName().c_str()); // Removes the file if the buffermanager does not have more buffers of the same file std::map<std::string, int*>::iterator it = _buffersByLog->find(buffer->fileName()); // If the file counter is zero it means there're no references to it and should be // deleted from disk (pe. commit), if the file is not referenced this will mean the // buffer comes from other buffermanager and should be removed. bool dropFile = false; if (it != _buffersByLog->end()) { int* count = it->second; if (*count <= 0) { dropFile = true; delete count; _buffersByLog->erase(it); } } else { dropFile = true; } if (dropFile) { std::string file = buffer->fileName(); std::string datadir = getSetting("DATA_DIR"); char* fullFilePath = combinePath(datadir.c_str(), file.c_str()); if (_log->isDebug()) _log->debug(2, "removing the log file: %s", fullFilePath); if (existFile(fullFilePath)) { if (!removeFile(fullFilePath)) { _log->error("An error ocurred removing the file: %s. Error Number: %d, Error description: %s", fullFilePath, errno, strerror(errno)); } } free(fullFilePath); } delete buffer; }
Boolean System::renameFile(const char* oldPath, const char* newPath) { if (exists(oldPath)) { removeFile(newPath); } return rename(oldPath, newPath) == 0; }
void VTKGridWriterTest::testEmptyGrid() { ParticleContainer* container = Factory::createEmptyParticleContainer(Factory::LinkedCell); LinkedCells* linkedCells = dynamic_cast<LinkedCells*> (container); assert(linkedCells != NULL); VTKGridWriter writer(2, "VTKGridWriterTest", *linkedCells); #ifdef ENABLE_MPI // in the parallel case we check only that the right files are written. // Their content should be right, if the sequential tests pass. int rank = 0; MPI_Comm_rank(MPI_COMM_WORLD, &rank); Domain domain(rank, NULL); writer.doOutput(container, NULL, &domain, 1, NULL); writer.doOutput(container, NULL, &domain, 2, NULL); MPI_Barrier(MPI_COMM_WORLD); if (rank == 0) { ASSERT_TRUE_MSG("Check that files are written in the right interval.", !fileExists("VTKGridWriterTest_1.pvtu")); ASSERT_TRUE_MSG("Check that files are written in the right interval.", fileExists("VTKGridWriterTest_2.pvtu")); removeFile("VTKGridWriterTest_2.pvtu"); int numProcs = 0; MPI_Comm_size(MPI_COMM_WORLD, &numProcs); for (int i = 0; i < numProcs; i++) { std::stringstream str; str << "VTKGridWriterTest_node" << i << "_2.vtu"; std::stringstream msg; msg << "Check that parallel files are written in the right interval. (File " << str.str() <<")"; ASSERT_TRUE_MSG(msg.str(), fileExists(str.str().c_str())); removeFile(str.str().c_str()); } } #else Domain domain(0, NULL); writer.doOutput(container, NULL, &domain, 1, NULL); ASSERT_TRUE_MSG("Check that files are written in the right interval.", !fileExists("VTKGridWriterTest_1.vtu")); writer.doOutput(container, NULL, &domain, 2, NULL); ASSERT_TRUE_MSG("Check that files are written in the right interval.", fileExists("VTKGridWriterTest_2.vtu")); removeFile("VTKGridWriterTest_2.vtu"); #endif }
Fifo::~Fifo() { disconnect(); if (exists(path_.c_str())) { if (!removeFile(path_.c_str())) { PLOG(ERROR) << "Error removing debug fifo file"; } } }