void Foam::calc(const argList& args, const Time& runTime, const fvMesh& mesh) { bool writeResults = !args.optionFound("noWrite"); IOobject Uheader ( "U", runTime.timeName(), mesh, IOobject::MUST_READ ); IOobject Theader ( "T", runTime.timeName(), mesh, IOobject::MUST_READ ); // Check U and T exists if (Uheader.headerOk() && Theader.headerOk()) { autoPtr<volScalarField> MachPtr; volVectorField U(Uheader, mesh); if (isFile(runTime.constantPath()/"thermophysicalProperties")) { // thermophysical Mach autoPtr<basicPsiThermo> thermo ( basicPsiThermo::New(mesh) ); volScalarField Cp = thermo->Cp(); volScalarField Cv = thermo->Cv(); MachPtr.set ( new volScalarField ( IOobject ( "Ma", runTime.timeName(), mesh ), mag(U)/(sqrt((Cp/Cv)*(Cp - Cv)*thermo->T())) ) ); } else { // thermodynamic Mach IOdictionary thermoProps ( IOobject ( "thermodynamicProperties", runTime.constant(), mesh, IOobject::MUST_READ, IOobject::NO_WRITE ) ); dimensionedScalar R(thermoProps.lookup("R")); dimensionedScalar Cv(thermoProps.lookup("Cv")); volScalarField T(Theader, mesh); MachPtr.set ( new volScalarField ( IOobject ( "Ma", runTime.timeName(), mesh ), mag(U)/(sqrt(((Cv + R)/Cv)*R*T)) ) ); } Info<< "Mach max : " << max(MachPtr()).value() << endl; if (writeResults) { MachPtr().write(); } } else { Info<< " Missing U or T" << endl; } }
Foam::fileName Foam::IOobject::filePath() const { if (instance().isAbsolute()) { fileName objectPath = instance()/name(); if (isFile(objectPath)) { return objectPath; } else { return fileName::null; } } else { fileName path = this->path(); fileName objectPath = path/name(); if (isFile(objectPath)) { return objectPath; } else { if ( time().processorCase() && ( instance() == time().system() || instance() == time().constant() ) ) { fileName parentObjectPath = rootPath()/caseName() /".."/instance()/db_.dbDir()/local()/name(); if (isFile(parentObjectPath)) { return parentObjectPath; } } if (!isDir(path)) { word newInstancePath = time().findInstancePath ( instant(instance()) ); if (newInstancePath.size()) { fileName fName ( rootPath()/caseName() /newInstancePath/db_.dbDir()/local()/name() ); if (isFile(fName)) { return fName; } } } } return fileName::null; } }
bool Project::Item::shouldBeAddedToTargetProject() const { return isFile(); }
FileLike* FilePath::file(void) { if (isFile()) { return (FileLike*)fb; } return NULL; }
TITANIUM_FUNCTION(File, isFile) { return get_context().CreateBoolean(isFile()); }
Foam::fvMesh::fvMesh(const IOobject& io) : polyMesh(io), surfaceInterpolation(*this), boundary_(*this, boundaryMesh()), lduPtr_(NULL), curTimeIndex_(time().timeIndex()), VPtr_(NULL), V0Ptr_(NULL), V00Ptr_(NULL), SfPtr_(NULL), magSfPtr_(NULL), CPtr_(NULL), CfPtr_(NULL), phiPtr_(NULL) { if (debug) { Info<< "Constructing fvMesh from IOobject" << endl; } // Check the existance of the cell volumes and read if present // and set the storage of V00 if (isFile(time().timePath()/"V0")) { V0Ptr_ = new DimensionedField<scalar, volMesh> ( IOobject ( "V0", time().timeName(), *this, IOobject::MUST_READ, IOobject::NO_WRITE ), *this ); V00(); } // Check the existance of the mesh fluxes, read if present and set the // mesh to be moving if (isFile(time().timePath()/"meshPhi")) { phiPtr_ = new surfaceScalarField ( IOobject ( "meshPhi", time().timeName(), *this, IOobject::MUST_READ, IOobject::AUTO_WRITE ), *this ); // The mesh is now considered moving so the old-time cell volumes // will be required for the time derivatives so if they haven't been // read initialise to the current cell volumes if (!V0Ptr_) { V0Ptr_ = new DimensionedField<scalar, volMesh> ( IOobject ( "V0", time().timeName(), *this, IOobject::NO_READ, IOobject::NO_WRITE, false ), V() ); } moving(true); } }
/** * @brief Arguments handling : All the parameters of the program are handled here (expect from the special arguments which are handled before) * * @param desc the Description we are about to change to handle the special args * @param argc the number of arguments passed to the program * @param argv the strings table of arguments passed to the program */ static inline void Option_handleArguments (SDescription *desc, int argc, char *argv[]) { char *configFileName = Description_getConfigFile (desc); long val; int opt; FILE *f; unsigned m_nb_args; char **m_argv; // First, we have to parse the XML config file if (configFileName != NULL) { if (Config_parseXML (desc, configFileName) == -1) { Log_output (-1, "Error: An error occured while parsing the XML config file.\n"); exit (EXIT_FAILURE); } } // Then, we can now handle other arguments in the command line optind = 1; /* Then, the final values have to be those of the command line */ while ((opt = getopt_long (argc, argv, "", option_list, NULL)) != -1) { switch (opt) { case 'a': // --summary Description_enableSummary(desc); break; case 'A': // --alloclib Description_setDynAllocLib(desc, optarg); break; case 'b': // --basename Description_setBaseName (desc, optarg); break; case 'B': // --verifylib Description_setVerificationLibraryName (desc, optarg); break; case 'c': // --cpupin parseCPUPinning (desc, optarg); break; case 'd': // --sizedummy val = Option_transformArgument (optarg); Description_setDummySize (desc, val); break; case 'D': // --output-dir Description_setOutputPath (desc, optarg); break; case 'e': // --endvector val = Option_transformArgument (optarg); Description_setEndVectorSize (desc, val); break; case 'f': // --kernelfunction Description_setDynamicFunctionName (desc, optarg); break; case 'F': // --no-eval-stack Description_disableEvalStack (desc); break; case 'g': // --output-same-dir Description_setOutputPath (desc, "."); break; case 'G': Description_setExecPath (desc, optarg); break; case 'i': // --stepvector val = Option_transformArgument (optarg); Description_setVectorSizeStep (desc, val); break; case 'I': // --info Description_parseInfoDisplayedInput (desc, optarg); break; case 'k': // --kernelname if (isFile (optarg)) { Description_setKernelFileNamesTabSize (desc, 1); Description_setKernelFileNameAt (desc, optarg, 0); } else if (isDirectory (optarg)) { parseDir (optarg, desc); } else { Log_output (-1, "Error: Cannot resolve kernel name filetype.\n"); exit (EXIT_FAILURE); } Description_setKernelFileName (desc, optarg); break; case 'l': // --logverbosity val = Option_transformArgument (optarg); Log_setVerbosity (val); break; case 'm': // --metarepetition val = Option_transformArgument (optarg); Description_setMetaRepetition (desc, val); break; case 'M': // --vectorspacing val = Option_transformArgument (optarg); Description_setVectorSpacing (desc, val); break; case 'N': // --no-output Description_setPromptOutputCsv (desc, 0); break; case 'o': // --log-output f = fopen (optarg, "w"); Log_setOutput (f); break; case 'O': // --nbprocess val = Option_transformArgument (optarg); if (Description_getNbProcess (desc) > 0 && Description_getNbProcess (desc) != val) { Log_output (-1, "Error: Number of processes already defined and not the same value\n"); exit (EXIT_FAILURE); } else { if (Description_getNbProcess (desc) < 0) { Description_setNbProcess (desc, val); } } break; case 'p': // --pagecollide val = Option_transformArgument (optarg); Description_setNbPagesForCollision (desc, val); break; case 'P': // --pagesize val = Option_transformArgument (optarg); Description_setPageSize (desc, val); break; case 'q': // --vectsurveyor parse_vect_surveyor (desc,optarg); break; case 'Q': // --executerepetition val = Option_transformArgument (optarg); Description_setExecuteRepets (desc, val); break; case 'r': // --repetition val = Option_transformArgument (optarg); Description_setRepetition (desc, val); break; case 's': // --startvector val = Option_transformArgument (optarg); Description_setStartVectorSize (desc, val); break; case 'S': // --maxstride val = Option_transformArgument (optarg); Description_setMaxStride (desc, val); break; case 't': // --omppath Description_setOmpPath (desc, optarg); break; case 'T': // --execname Description_setExecFileName (desc, optarg); break; case 'u': // --execargs m_argv = getArgs (desc, optarg, &m_nb_args); Description_setExecArgc (desc, m_nb_args); Description_setExecArgv (desc, m_argv); break; case 'U': // --suppress-output Description_setSuppressOutput (desc, 1); break; case 'v': // --iteration-count val = Option_transformArgument (optarg); Description_setIterationCount (desc, val); Description_iterationCountEnable (desc); break; case 'V': // --execoutput Description_setOutputFileStream (desc, optarg); break; case 'w': // --initfunction Description_setKernelInitFunctionName (desc, optarg); break; case 'W': // --data-size /* If user specifies "float", let's allocate sizeof(float) */ if (strncmp ("float", optarg, STRBUF_MAXLEN) == 0) { Description_setVectorElementSize (desc, sizeof (float)); } /* If he specifies "double", let's allocate sizeof(double) */ else if (strncmp ("double", optarg, STRBUF_MAXLEN) == 0) { Description_setVectorElementSize (desc, sizeof (double)); } /* Else, he must have specified a numeric constant */ else { val = Option_transformArgument (optarg); Description_setVectorElementSize (desc, val); } break; case 'x': // --nbsizes Description_nbSizesEnable (desc); parseVectorSizes (desc, optarg); break; case 'X': // --no-thread-pin Description_pinThreadDisable (desc); break; case 'y': // --all-print-out Description_setAllPrintOut (desc, 1); break; case 'Y': // --all-metric-output Description_allProcessOutputEnable (desc); break; case 'z': // --resumeid val = Option_transformArgument (optarg); Description_setResumeId (desc, val); break; default: assert (argv != NULL && argv[0] != 0); break; } } }
static size_t eListInsert(intptr_t EditorID, wchar_t* filename) { bool newFile = !isFile (filename); return (eList->insert (EditorID, findLngID (filename), filename, newFile)); }
static bool runCompiler (const EditorInfoEx *ei, const TLang *lng, const wchar_t *fn, const wchar_t *path, const wchar_t *title, const TExec *e) { wchar_t cwd[NM] = L"", baseFile[NM] = L""; if (!e->enable.empty()) { wchar_t temp[NM]; makeCmdLine (false, baseFile, e->enable, path, fn); bool enable = isFile (baseFile); if (!enable && e->searchBase && findBaseFile (path, baseFile, temp)) wcscpy (baseFile, temp); } if (!makeCmdLine (true, cmd, e->cmd, path, fn, makeTitle (title, 30, path, fn))) return (false); wcscpy(cmdpath, path); wchar_t temp[NM]; wcscpy(temp, cmd); ExpandEnvironmentStrings (temp, cmd, NM); if (e->saveType != saNone) { if (e->saveType == saCurrent) { wchar_t witypename[NM]; wchar_t winame[NM]; WindowInfoEx wi; wi.TypeName = witypename; wi.TypeNameSize = NM; wi.Name = winame; wi.NameSize = NM; wi.Pos = -1; Info.AdvControl (&MainGuid, ACTL_GETWINDOWINFO, 0, (void *) &wi); if (wi.Type == WTYPE_EDITOR && (wi.Flags & WIF_MODIFIED)) if (!Info.EditorControl (-1, ECTL_SAVEFILE, 0, nullptr)) return (false); } else { if (!SaveAll ()) { const wchar_t *MsgItems[] = { GetMsg (MTitle), GetMsg (MSaveError), GetMsg (MContinue) }; if (Info.Message (&MainGuid, &RunCompilerGuid, FMSG_MB_YESNO, nullptr, MsgItems, _countof (MsgItems), 0)) return (false); } } } if (e->cd != cdNone) { wchar_t newDir[NM] = L"", *p; if (e->cd == cdFile) p = wcsrchr (wcscpy (newDir, fn), L'\\'); else if ((e->cd == cdBase) && *baseFile) p = wcsrchr (wcscpy (newDir, baseFile), L'\\'); if (p) *p = 0; if (*newDir) { GetCurrentDirectory (_countof (cwd), cwd); SetCurrentDirectory (newDir); } } if (compilerOutColl) compilerOutColl->removeAll (); else compilerOutColl = new TCollection<TOutputLine>; if (errColl) errColl->removeAll (); else errColl = new TCollection<TErrData>; compilerOutP = -1; execute (compilerOutColl, cmd, e->echo); size_t n = compilerOutColl->getCount (); if (n) { intptr_t nErr = 0, aj = -1; compilerOut = new FarMenuItemEx[compilerOutN = n + 1]; for (size_t i = 0; i < n; i++) { const TOutputLine *outData = (*compilerOutColl)[i]; const wchar_t *line = outData->line; compilerOut[i].Text = line; compilerOut[i].Flags = MIF_DISABLE; compilerOut[i].UserData = 0; wchar_t compiler[MAX_STR_LEN]; wcscpy (compiler, e->compiler); wchar_t *pp, *p = compiler; bool found = false; while ((pp = wcschr (p, L',')) != nullptr) { *pp = 0; if (parseError (lng, p, path, fn, line, i, aj)) { nErr++; found = true; } p = pp + 1; if (found) break; } if (!found && parseError (lng, p, path, fn, line, i, aj)) nErr++; } if ((aj >= 0) && ((e->jumpType == jtFirst)) || ((e->jumpType == jtSmart) && (nErr == 1))) jumpToError (ei, path, aj, true); else { if (aj < 0) { if (compilerOut[n - 1].Text[0] == 0) { compilerOutN--; n--; } compilerOut[n].Text = L""; compilerOut[n].Flags = MIF_SELECTED; } else compilerOutN--; if ((e->jumpType == jtMenu) || (e->jumpType == jtSmart)) showCompileOut (ei, path); } } else if (compilerOut) { delete compilerOutColl; compilerOutColl = nullptr; delete[] compilerOut; compilerOut = nullptr; } if (*cwd) SetCurrentDirectory (cwd); return (true); }
bool Project::Item::isImageFile() const { return isFile() && ImageFileFormat::findImageFormatForFileExtension (getFile()) != nullptr; }
QVector<BootstrapModelPrivate::Lines*> BootstrapModelPrivate::loadDefaultBootstrapServers() { auto servers = QVector<BootstrapModelPrivate::Lines*>(); /* get the bootstrap directory */ QString bootstrapDirPath = QStandardPaths::locate( QStandardPaths::DataLocation, "bootstrap", QStandardPaths::LocateDirectory ); QDir bootstrapDir = QDir(bootstrapDirPath); auto bootstrapFiles = QVector<QFileInfo>(); // Main bootstrap servers file auto mainBootstrapFile = QFileInfo(bootstrapDir.path() + "/servers.json"); if (mainBootstrapFile.exists() && mainBootstrapFile.isFile()) { bootstrapFiles << mainBootstrapFile; } // Secondary bootstrap servers files auto secondaryBootstrapServersDir = QFileInfo(bootstrapDir.path() + "/servers.json.d/"); if (secondaryBootstrapServersDir.exists() && secondaryBootstrapServersDir.isDir()) { QDirIterator dirIter( secondaryBootstrapServersDir.path(), QDirIterator::Subdirectories ); while (dirIter.hasNext()) { dirIter.next(); auto secBootstrapFileInfo = QFileInfo(dirIter.filePath()); if (secBootstrapFileInfo.isFile() && secBootstrapFileInfo.suffix() == "json") { bootstrapFiles << secBootstrapFileInfo; } } } //Parse JSON files foreach(const auto fileInfo, bootstrapFiles) { QFile bootstrapFile(fileInfo.filePath()); if (bootstrapFile.open(QIODevice::ReadOnly | QIODevice::Text)) { auto jsonDoc = QJsonDocument::fromJson(bootstrapFile.readAll()); bootstrapFile.close(); if (jsonDoc.isNull() == false && jsonDoc.isArray() == true) { QJsonArray jsonArray = jsonDoc.array(); foreach(const auto jsonValue, jsonArray) { auto hostObject = jsonValue.toObject(); auto hostValue = hostObject.value("host"); auto portValue = hostObject.value("port"); if (hostValue.isUndefined() == false && hostValue.isString() && portValue.isUndefined() == false && portValue.isDouble()) { BootstrapModelPrivate::Lines* server = new BootstrapModelPrivate::Lines(); server->hostname = hostValue.toString(); server->port = portValue.toInt(-1); servers << server; } }
int isPlaylist(char * utf8file) { if(isFile(utf8file,NULL)) { return hasSuffix(utf8file,PLAYLIST_FILE_SUFFIX); } return 0; }
// Does the name exist in the filing system? bool Foam::exists(const fileName& name, const bool checkGzip) { return mode(name) || isFile(name, checkGzip); }
char const *findConfig(char const *shell, char const *Type) // 005, 007 { static char name[1024]; static char exe[256]; char *p; // Resolve the text of the file extension (if any) if (NULL != Type) { sprintf(exe, ".%s", Type); Type = exe; } else { Type = ""; } // Look for the file in the home account if (NULL != Tenv::appGet("HOME")) { sprintf(name, "%s/.sirerc/%s%s", Tenv::appGet("HOME"), shell, Type); // 007 if (isFile(name)) { return (name); } } // Look for the file in the group account if (NULL != Tenv::appGet("GROUP")) { #if defined(INTEL_NT) || defined (INTEL_9X) || defined (CYGWIN) sprintf(name, "%s/group/%s/sire/%s%s", Tenv::appGet("ROOTDIR"), Tenv::appGet("GROUP"), shell, Type); // 007 #else sprintf(name, "%s/usr/group/%s/sirerc/%s%s", Tenv::appGet("ROOTDIR"), Tenv::appGet("GROUP"), shell, Type); // 007 #endif if (isFile(name)) { return (name); } } // Look for the file in the global account #if defined(INTEL_NT) || defined (INTEL_9X) || defined (CYGWIN) sprintf(name, "%s/sire/%s%s", Tenv::appGet("ROOTDIR"), shell, Type); // 007 #else sprintf(name, "%s/usr/sirerc/%s%s", Tenv::appGet("ROOTDIR"), shell, Type); // 007 #endif if (isFile(name)) { return (name); } // Look for the file in the same directory as the executable strcpy(name, Tenv::appGet("SIRE")); if (NULL == (p = strrchr(name, *DIR_SEP))) { // Assume it is in the current directory sprintf(name, "%s/sirerc/%s%s", Tenv::appGet("PWD"), shell, Type); } else { // Append to the path sprintf(p+1, "sirerc/%s%s", shell, Type); } if (isFile(name)) { return (name); } return (NULL); }
void NBFolderView::doOpen( QString loc ) { if ( loc.startsWith( "NB://" ) ) { setCursor( QCursor( Qt::WaitCursor ) ); qApp->processEvents(); fsModel->setRootPath( loc ); setCursor( QCursor( Qt::ArrowCursor ) ); return; } if ( not isReadable( loc ) ) { QString title = tr( "Access Error" ); QString text; text += tr( "<p>You do not have enough permissions to open the %1:</p><p><center><b>%2</b></center></p>" ); text += tr( "<p>Please change the permissions of the %1 to enter it." ); if ( isDir( loc ) ) text = text.arg( "directory" ).arg( loc ); else text = text.arg( "file" ).arg( loc ); if ( fsModel->rootPath().isEmpty() ) text += tr( "<br>Instead, I will be opening your <b>home</b> folder for you.</p>" ); NBMessageDialog::error( this, title, text ); setCursor( QCursor( Qt::WaitCursor ) ); fsModel->setRootPath( NBXdg::home() ); setCursor( QCursor( Qt::ArrowCursor ) ); return; } setCursor( QCursor( Qt::WaitCursor ) ); qApp->processEvents(); if ( isDir( loc ) ) { qDebug() << "Opening dir:" << loc.toLocal8Bit().data(); fsModel->setRootPath( loc ); } else if ( isFile( loc ) ) { if ( isExec( loc ) and not isText( loc ) ) { /* * * We make sure that @v loc is really an executable file, * i.e it is one of x-exec or x-sharedlib or something * of the sort and not a shellscript or jpg file with exec * permissions * */ qDebug( "Executing %s... [%s]", loc.toLocal8Bit().data(), ( QProcess::startDetached( loc ) ? "DONE" : " FAILED" ) ); } else { NBAppFile app = NBAppEngine::instance()->xdgDefaultApp( mimeDb.mimeTypeForFile( loc ) ); if ( not app.isValid() ) doOpenWithCmd(); QStringList exec = app.execArgs(); // Prepare @v exec if ( app.takesArgs() ) { if ( app.multipleArgs() ) { int idx = exec.indexOf( "<#NEWBREEZE-ARG-FILES#>" ); exec.removeAt( idx ); exec.insert( idx, loc ); } else { int idx = exec.indexOf( "<#NEWBREEZE-ARG-FILE#>" ); exec.removeAt( idx ); exec.insert( idx, loc ); } } else { exec << loc; } qDebug( "Opening file: %s [%s]", loc.toLocal8Bit().data(), ( QProcess::startDetached( exec.takeFirst(), exec ) ? "DONE" : " FAILED" ) ); } } else { QString title = QString( "Error opening file" ); QString text = QString( "I really do not have any idea how to open <tt><b>%1</b></tt>" ).arg( loc ); NBMessageDialog::error( this, title, text ); qDebug() << "Cannot open file:" << loc.toLocal8Bit().data(); return; } setCursor( QCursor( Qt::ArrowCursor ) ); setFocus(); };
void fileList(cgiScript & script, string title="File In: " ) { cgiInput & args = script.ClientArguments(); cgiTemplates htmlDoc; title += m_urlDir; // fileDir(); writelog("Loading Templates/filelist.htmp"); htmlDoc.load("Templates/filelist.htmp"); char * Rows[2] = { "oddcell", "evencell" }; writelog("Writing top of page"); script << ocString(htmlDoc.getParagraph("top")) .replace( "__REPORT_TITLE_GOES_HERE", title.c_str() ) .replaceAll( "filePick.cgi", m_exe_name.c_str() ) << endl; ocString headitem = htmlDoc.getParagraph("headitem"); string rowsep = htmlDoc.getParagraph("rowsep"); writelog("Writing headers"); script << headitem.replace("__hcell_label","File"); script << headitem.replace("__hcell_label","Action"); script << headitem.replace("__hcell_label","Delete"); if( fs.openDir(m_fileDir) ) { ocDirectory & entries = fs.getDirectoryEntries(); if(args.count("File") > 0) // show the uploaded file first { sort( entries.begin(), entries.end(), datesort ); } else // default to alphnumeric sort { sort( entries.begin(), entries.end(), namesort ); } // new code to limit the view int iMax = entries.size()?entries.size():0; if( iMax > 20 ) iMax = 20; // default to limit show to 20 items bool fileFound = false; if( args.count("showall") ) iMax = entries.size(); for( int iRow = 0; iRow < iMax || (!fileFound && iRow < entries.size()); ++iRow ) { if(isFile(entries[iRow].name)) // make sure it's a file { fileFound = true; string imgPath = m_fileDir; imgPath +="/"; imgPath += entries[iRow].name; string imgLink = entries[iRow].name; string relLink = m_urlDir; relLink +="/"; relLink += entries[iRow].name; ocString row = htmlDoc.getParagraph(Rows[ iRow % 2 ] ); string actions = fLnk.replace( "_file_", imgLink.c_str()); actions += sLnk.replace( "_file_", relLink.c_str() ); script << rowsep; script << row.replace( "__cell_data", entries[iRow].name.c_str() ); script << row.replace( "__cell_data", actions.c_str() ); script << row.replace( "__cell_data", delLink.replaceAll( "_file_", entries[iRow].name.c_str() ).c_str() ); script << endl; } } // end for } script << htmlDoc.getParagraph("bottom") << endl; }
void NBFolderView::doOpen( QModelIndex idx ) { /* This slot is triggered when the user double clicks or presses enter */ Q_UNUSED( idx ); QList<QModelIndex> selectedList = getSelection(); foreach( QModelIndex index, selectedList ) { QString fileToBeOpened = fsModel->nodePath( index ); if ( not isReadable( fileToBeOpened ) ) { QString title = tr( "Access Error" ); QString text = tr( "You do not have enough permissions to open <b>%1</b>. " ).arg( baseName( fileToBeOpened ) ); if ( isDir( fileToBeOpened ) ) text += tr( "Please change the permissions of the directory to enter it." ); else text += tr( "Please change the permissions of the file to edit/view it." ); NBMessageDialog::error( this, title, text ); return; } if ( isDir( fileToBeOpened ) ) { qDebug() << "Opening dir:" << fileToBeOpened.toLocal8Bit().data(); if ( index == idx ) { setCursor( QCursor( Qt::WaitCursor ) ); fsModel->setRootPath( fileToBeOpened ); setCursor( QCursor( Qt::ArrowCursor ) ); } else { emit newTab( fileToBeOpened ); } } else if ( isFile( fileToBeOpened ) ) { if ( isExec( fileToBeOpened ) and not isText( fileToBeOpened ) ) { /* * * We make sure that @v fileToBeOpened is really an executable file, * i.e it is one of shellscript, install file, or x-exec or x-sharedlib * or something of the sort and not a jpg file with exec perms * */ qDebug( "Executing %s... [%s]", fileToBeOpened.toLocal8Bit().data(), ( QProcess::startDetached( fileToBeOpened ) ? "DONE" : " FAILED" ) ); } else { NBAppFile app = NBAppEngine::instance()->xdgDefaultApp( mimeDb.mimeTypeForFile( fileToBeOpened ) ); if ( not app.isValid() ) doOpenWithCmd(); QStringList exec = app.execArgs(); // Prepare @v exec if ( app.takesArgs() ) { if ( app.multipleArgs() ) { int idx = exec.indexOf( "<#NEWBREEZE-ARG-FILES#>" ); exec.removeAt( idx ); exec.insert( idx, fileToBeOpened ); } else { int idx = exec.indexOf( "<#NEWBREEZE-ARG-FILE#>" ); exec.removeAt( idx ); exec.insert( idx, fileToBeOpened ); } } else { exec << fileToBeOpened; } qDebug( "Opening file: %s [%s]", fileToBeOpened.toLocal8Bit().data(), ( QProcess::startDetached( exec.takeFirst(), exec ) ? "DONE" : " FAILED" ) ); } } else { QString title = QString( "Error" ); QString text = QString( "I really do not have any idea how to open <b>%1</b>." ).arg( index.data().toString() ); NBMessageDialog::error( this, title, text ); qDebug() << "Cannot open file:" << fileToBeOpened.toLocal8Bit().data(); return; } }
Foam::word Foam::Time::findInstance ( const fileName& dir, const word& name, const IOobject::readOption rOpt, const word& stopInstance ) const { // Note: if name is empty, just check the directory itself // check the current time directory if ( name.empty() ? isDir(path()/timeName()/dir) : ( isFile(path()/timeName()/dir/name) && IOobject(name, timeName(), dir, *this).headerOk() ) ) { if (debug) { Info<< "Time::findInstance" "(const fileName&, const word&, const IOobject::readOption)" << " : found \"" << name << "\" in " << timeName()/dir << endl; } return timeName(); } // Search back through the time directories to find the time // closest to and lower than current time instantList ts = times(); label instanceI; for (instanceI = ts.size()-1; instanceI >= 0; --instanceI) { if (ts[instanceI].value() <= timeOutputValue()) { break; } } // continue searching from here for (; instanceI >= 0; --instanceI) { if ( name.empty() ? isDir(path()/ts[instanceI].name()/dir) : ( isFile(path()/ts[instanceI].name()/dir/name) && IOobject(name, ts[instanceI].name(), dir, *this).headerOk() ) ) { if (debug) { Info<< "Time::findInstance" "(const fileName&, const word&, const IOobject::readOption)" << " : found \"" << name << "\" in " << ts[instanceI].name()/dir << endl; } return ts[instanceI].name(); } // Check if hit minimum instance if (ts[instanceI].name() == stopInstance) { if (debug) { Info<< "Time::findInstance" "(const fileName&, const word&" ", const IOobject::readOption, const word&)" << " : hit stopInstance " << stopInstance << endl; } if (rOpt == IOobject::MUST_READ) { FatalErrorIn ( "Time::findInstance" "(const fileName&, const word&" ", const IOobject::readOption, const word&)" ) << "Cannot find file \"" << name << "\" in directory " << dir << " in times " << timeName() << " down to " << stopInstance << exit(FatalError); } return ts[instanceI].name(); } } // not in any of the time directories, try constant // Note. This needs to be a hard-coded constant, rather than the // constant function of the time, because the latter points to // the case constant directory in parallel cases if ( name.empty() ? isDir(path()/constant()/dir) : ( isFile(path()/constant()/dir/name) && IOobject(name, constant(), dir, *this).headerOk() ) ) { if (debug) { Info<< "Time::findInstance" "(const fileName&, const word&, const IOobject::readOption)" << " : found \"" << name << "\" in " << constant()/dir << endl; } return constant(); } if (rOpt == IOobject::MUST_READ) { FatalErrorIn ( "Time::findInstance" "(const fileName&, const word&, const IOobject::readOption)" ) << "Cannot find file \"" << name << "\" in directory " << dir << " in times " << timeName() << " down to " << constant() << exit(FatalError); } return constant(); }
bool CombineFileManager::isCombineArchive(const QString &pFileName) const { // Return whether the given file is a COMBINE archive return isFile(pFileName); }
int main(int argc, char* argv[]) {getCurrentDir(self_dir);self_path=self_dir+String(path_delim)+executable_name; CWD=toString(self_dir); CWDN=basename(self_dir); prepareLogDir(); //////////////////////////////// Opt parse//////////////////////////////////////////// StringArray args; for(int i = 1; i < argc; i++){args.push_back(argv[i]);} bool skipcount=false; bool noopt=false; { //Scope for the following objects Options inc_obj("-inc","--increment-value"); Options linc_obj("-linc","--line-increment-value"); Options si_obj("-i","-si","--index","--start-index"); Options ei_obj("-ei","--end-index"); Options ifl_obj("-ifl","--index-field-length"); Options ifp_obj("-ifp","--index-field-precision"); Options iff_obj("-iff","--index-field-filler"); Options ns_obj("-ns","--name-string"); Options nsf_obj("-ns/f","--name-string-file"); Options sl_obj("-l","-sl","--line","--start-line"); Options el_obj("-el","--end-line"); Options ss_obj("-ss","--search-string"); Options ss_file_obj("-ss/f","--search-string-file"); Options rs_obj("-rs","--replace-string"); Options rs_file_obj("-rs/f","--replace-string-file"); Options re_obj("-re","--regex"); Options dp_obj("-dp","--depth"); Options if_obj("-if","--index-flags"); for(int i = 0; i < (int)args.size(); i++){ if(skipcount){skipcount=false;continue;} String opt=toLower(String(args[i])); if(!noopt){ if(opt=="-h"||opt=="--help"){ printe help_message; return 0; } else if(opt=="-v"||opt=="--version"){ printe version_info; return 0; } else if(opt=="-q"||opt=="--quiet"){ quiet=true; } else if(opt=="-fo"||opt=="--file-only"){ file_only=true; } else if(opt=="-do"||opt=="--directory-only"){ directory_only=true; } else if(opt=="-ed"||opt=="--exclude-directory"){ exclude_directory=true; } else if(opt=="-inc"||opt=="--increment-value"){ checkArgAvailability(args,i+1); mustBeAPositiveNumber("Increment Value","\nNegative increment i.e decrement will be available using name string rule:\n\ "+path_delim+"-i"+path_delim+", "+path_delim+"-ir"+path_delim+", "+path_delim+"-id"+path_delim+" etc..\n",args[i+1]); inc=stringTo<decltype(inc)>(args[i+1]); skipcount=true; inc_obj.count++; if(inc_obj.count>1){printWarningLog("Increment value overwritten");} } else if(opt=="-linc"||opt=="--line-increment-value"){ checkArgAvailability(args,i+1); mustBeAPositiveInteger("Line Increment Value",args[i+1]); linc=stringTo<decltype(linc)>(args[i+1]); skipcount=true; linc_obj.count++; if(linc_obj.count>1){printWarningLog("Line increment value overwritten");} } else if(opt=="-i"||opt=="-si"||opt=="--index"||opt=="--start-index"){ checkArgAvailability(args,i+1); mustBeANumber("Start Index",args[i+1]); start_index=stringTo<decltype(start_index)>(args[i+1]); current_index=start_index; current_index_rd=start_index; reverse_index=start_index; reverse_index_rd=start_index; DIRECTORY_INDEX=start_index; DIRECTORY_REVERSE_INDEX=start_index; skipcount=true; si_obj.count++; if(si_obj.count>1){printWarningLog("Start index overwritten");} } else if(opt=="-ei"||opt=="--end-index"){ checkArgAvailability(args,i+1); mustBeANumber("End Index",args[i+1]); end_index=stringTo<decltype(end_index)>(args[i+1]); skipcount=true; ei_obj.count++; if(ei_obj.count>1){printWarningLog("End index overwritten");} } else if(opt=="-if"||opt=="--index-flags"){ checkArgAvailability(args,i+1); parseIndexFlags(args[i+1]); skipcount=true; if_obj.count++; if(if_obj.count>1){printWarningLog("Override occurred in Index flags");} } else if(opt=="-ifl"||opt=="--index-field-length"){ checkArgAvailability(args,i+1); mustBeAPositiveInteger("Index field length",args[i+1]); index_field_length=stringTo<decltype(index_field_length)>(args[i+1]); skipcount=true; ifl_obj.count++; if(ifl_obj.count>1){printWarningLog("Index field length overwritten");} } else if(opt=="-ifp"||opt=="--index-field-precision"){ checkArgAvailability(args,i+1); mustBeAPositiveInteger("Index field precision",args[i+1]); IFP=stringTo<decltype(IFP)>(args[i+1]); skipcount=true; ifp_obj.count++; if(ifp_obj.count>1){printWarningLog("Index field precision overwritten");} } else if(opt=="-iff"||opt=="--index-field-filler"){ checkArgAvailability(args,i+1); mustBeAValidSingleCharacter("Index field filler",args[i+1]); IFF=stringTo<decltype(IFF)>(args[i+1]); IFF=replaceStringAll(IFF,"\\",""); skipcount=true; iff_obj.count++; if(iff_obj.count>1){printWarningLog("Index field filler overwritten");} } else if(opt=="-ns"||opt=="--name-string"){ checkArgAvailability(args,i+1); name_string=args[i+1]; skipcount=true; ns_obj.count++; if(ns_obj.count>1){printWarningLog("Name string overwritten");} } else if(opt=="-ns/f"||opt=="--name-string-file"){ checkArgAvailability(args,i+1); name_string_file=args[i+1]; skipcount=true; nsf_obj.count++; if(nsf_obj.count>1){printErrorLog("Only one name string file is allowed");Exit(1);} } else if(opt=="-ns/fn"||opt=="--name-string-file-null-terminated"){ checkArgAvailability(args,i+1); name_string_file=args[i+1]; nsf_n=true; skipcount=true; nsf_obj.count++; if(nsf_obj.count>1){printErrorLog("Only one name string file is allowed");Exit(1);} } else if(opt=="-l"||opt=="-sl"||opt=="--line"||opt=="--start-line"){ checkArgAvailability(args,i+1); mustBeAPositiveInteger("Start Line",args[i+1]); start_line=stringTo<decltype(start_line)>(args[i+1]); current_line=start_line; skipcount=true; sl_obj.count++; if(sl_obj.count>1){printWarningLog("Start line overwritten");} } else if(opt=="-lv"||opt=="-slv"||opt=="--line-reverse"||opt=="--start-line-reverse"){ checkArgAvailability(args,i+1); mustBeAPositiveInteger("Start Line",args[i+1]); start_line=stringTo<decltype(start_line)>(args[i+1]); current_line=start_line; skipcount=true; reverse_line=true; sl_obj.count++; if(sl_obj.count>1){printWarningLog("Start line overwritten");} } else if(opt=="-el"||opt=="--end-line"){ checkArgAvailability(args,i+1); mustBeAPositiveInteger("End Line",args[i+1]); end_line=stringTo<decltype(end_line)>(args[i+1]); skipcount=true; el_obj.count++; if(el_obj.count>1){printWarningLog("End line overwritten");} } else if(opt=="-elv"||opt=="--end-line-reverse"){ checkArgAvailability(args,i+1); mustBeAPositiveInteger("End Line",args[i+1]); end_line=stringTo<decltype(end_line)>(args[i+1]); skipcount=true; reverse_line=true; el_obj.count++; if(el_obj.count>1){printWarningLog("End line overwritten");} } else if(opt=="-ss"||opt=="--search-string"){ checkArgAvailability(args,i+1); search_string.push_back(args[i+1]); fixed_ss.push_back(false); skipcount=true; ss_obj.count++; ///multple is allowed } else if(opt=="-ss/f"||opt=="--search-string-file"){ checkArgAvailability(args,i+1); search_string_file=args[i+1]; skipcount=true; if(isFile(search_string_file)){ StringArray temp=getLineFromFileAndReturnVector(search_string_file); ///append temp to search_string search_string.insert(search_string.end(),temp.begin(),temp.end()); ///Populate fixed_ss with same number of boolean value for(Int i=0;i<(Int)temp.size();i++){ fixed_ss.push_back(false); } } else{ printErrorLog("Search string file not found: "+search_string_file); Exit(1); } ss_file_obj.count++; ///multple is allowed } else if(opt=="-ssf"||opt=="--search-string-fixed"){ checkArgAvailability(args,i+1); search_string.push_back(args[i+1]); fixed_ss.push_back(true); skipcount=true; ss_obj.count++; ///multple is allowed } else if(opt=="-ssf/f"||opt=="--search-string-fixed-file"){ checkArgAvailability(args,i+1); search_string_file=args[i+1]; skipcount=true; if(isFile(search_string_file)){ StringArray temp=getLineFromFileAndReturnVector(search_string_file); ///append temp to search_string search_string.insert(search_string.end(),temp.begin(),temp.end()); ///Populate fixed_ss with same number of boolean value for(Int i=0;i<(Int)temp.size();i++){ fixed_ss.push_back(true); } } else{ printErrorLog("Search string file not found: "+search_string_file); Exit(1); } ss_file_obj.count++; ///multple is allowed } else if(opt=="-rs"||opt=="--replace-string"){ checkArgAvailability(args,i+1); replace_string.push_back(args[i+1]); skipcount=true; rs_obj.count++; ///multple is allowed } else if(opt=="-rs/f"||opt=="--replace-string-file"){ checkArgAvailability(args,i+1); replace_string_file=args[i+1]; skipcount=true; if(isFile(replace_string_file)){ StringArray temp=getLineFromFileAndReturnVector(replace_string_file); replace_string.insert(replace_string.end(),temp.begin(),temp.end()); } else{ printErrorLog("Replace string file not found: "+replace_string_file); Exit(1); } rs_file_obj.count++; ///multple is allowed } else if(opt=="-re" || opt == "--regex"){ checkArgAvailability(args,i+1); re_type=toLower(args[i+1]); skipcount=true; re_obj.count++; if(re_obj.count>1){printWarningLog("Regex mode overwritten");} } else if(opt=="-rel"||opt=="--regex-locale"){ re_locale=true; } else if(opt=="-dp"||opt=="--depth"){ checkArgAvailability(args,i+1); mustBeAnInteger("Depth",args[i+1]); depth=stringTo<decltype(depth)>(args[i+1]); if(depth<0){depth=std::numeric_limits<Int>::max();} skipcount=true; dp_obj.count++; if(dp_obj.count>1){printWarningLog("Directory depth overwritten");} } else if(opt=="-cd"||opt=="--count-directory"){ count_directory=true; } else if(opt=="-cf"||opt=="--count-file"){ count_file=true; } else if(opt=="-s"||opt=="--sort"){ sort=true; sort_type="default"; } else if(opt=="-s/g"||opt=="--sort/g"){ sort=true; sort_type="general"; } else if(opt=="-s/n"||opt=="--sort/n"){ sort=true; sort_type="natural"; } else if(opt=="-s/none"||opt=="--sort/none"){ sort=true; sort_type="none"; } else if(opt=="-y"||opt=="--yes"){ all_yes=true; } else if(opt=="-fl"||opt=="--follow-link"){ follow_symlink=true; } else if(opt=="-shop"||opt=="--show-options"){ show_options=true; } else if(opt=="-f"||opt=="--force"){ force=true; } else if(opt=="-u"||opt=="--undo"){ undo=true; } else if(opt=="-sim"||opt=="--simulation"){ simulation=true; } else if(opt=="--"){ noopt=true; } else if(opt[0]=='-'){ printErrorLog("Invalid Option: "+opt); Exit(1); } else { files.push_back(String(args[i])); } } else {
static void testIsFile(void) { test(isFile("src/filelib.c"), true); test(isFile("."), false); test(isFile("xyzzy.c"), false); }
void RetroArchTools::on_dir2m3u_genbutton_clicked() { d2m3udata_current.extension = ui->dir2m3u_extbox->text(); d2m3udata_current.outpath = ui->m3u_outbox->text(); d2m3udata_current.rompath = ui->dir2m3u_rombox->text(); d2m3udata_current.name = ui->dir2m3u_name->text(); if (!inputExists(d2m3udata_current.name)) { QMessageBox::warning(this,tr("Error!"),tr("Please input the name of the multi-disk game.")); return; } if (!inputExists(d2m3udata_current.extension) || d2m3udata_current.extension == ".") { QMessageBox::warning(this,tr("Error!"),tr("Please input the rom extension.")); return; } if (!inputExists(d2m3udata_current.outpath)) { QMessageBox::warning(this,tr("Error!"),tr("Please input the output path for the m3u.")); return; } if (!inputExists(d2m3udata_current.rompath)) { QMessageBox::warning(this,tr("Error!"),tr("Please select the folder containing the rom/images used to create the m3u file.")); return; } if (!fileExists(d2m3udata_current.outpath) || isFile(d2m3udata_current.outpath)) { QMessageBox::warning(this,tr("Error!"),tr("Cannot find output directory!")); return; } if (!fileExists(d2m3udata_current.rompath) || isFile(d2m3udata_current.rompath)) { QMessageBox::warning(this,tr("Error!"),tr("Cannot find rom directory!")); return; } if (d2m3udata_current.extension[0] != '.') { QMessageBox::warning(this,tr("Error!"),tr("File extension must begin with a '.'")); return; } QString m3ufile = QDir(d2m3udata_current.outpath).filePath(d2m3udata_current.name + ".m3u"); QFile m3u(m3ufile); QDir d2m3u_romdir(d2m3udata_current.rompath); QStringList filters; filters << "*" + d2m3udata_current.extension; QFileInfoList *d2m3u_roms = new QFileInfoList(d2m3u_romdir.entryInfoList(filters)); if (m3u.open(QFile::WriteOnly | QFile::Truncate)) { QTextStream m3u_out(&m3u); for(const auto &romfile : *d2m3u_roms) { m3u_out << romfile.fileName() + "\n"; } m3u.close(); } else { QMessageBox::warning(this,tr("Error!"),tr("Error writing to m3u (check the file isn't being used somewhere)")); return; } delete d2m3u_roms; QMessageBox::information(this,tr("Finished!"),"m3u file created at " + m3ufile); }
int main(int argc,char **argv) { long i,j; char fName[255]; char outname[255]; char outdir[255]; char fname[255]; char tmpname[255]; int Opt_hasFName=0; int Opt_outName=0; int Opt_outDir=0; int Opt_info=0; std::vector<std::string> Opt_to; if (argc==1) Usage(argv[0]); for (i=1;i<argc;) { if (argv[i][0]!='-') { strcpy(fName,argv[i]); Opt_hasFName=1; i++; } else if (i==1) { fprintf (stderr,"First argument must be a filename.\n"); Usage(argv[0]); } else if (!strcmp(argv[i],"-cosmo")) { double val[6]; if (argc<i+6) { fprintf(stderr,"Invalid arguments for option '-cosmo'.\n"); Usage(argv[0]); } for (j=1;j<5;j++) val[j-1]=atof(argv[i+j]); if (!isFile(argv[i+5])) cosmoD_init(val[0],val[1],val[2],val[3],atof(argv[i+5]),NULL); else cosmoD_init(val[0],val[1],val[2],val[3],-1,argv[i+5]); i+=6; } else if (!strcmp(argv[i],"-info")) { i++; Opt_info=1; } else if (!strcmp(argv[i],"-outName")) { i++; if ((i==argc)||(argv[i][0]=='-')) { printf ("\noption '-outName' needs an argument.\n"); Usage(argv[0]); } Opt_outName=1; strcpy(outname,argv[i]); i++; } else if (!strcmp(argv[i],"-outDir")) { Opt_outDir=1; i++; if ((argc==i)||(argv[i][0]=='-')) { fprintf (stderr,"I Expect a filename as argument of '-outDir'\n"); Usage(argv[0]); } strcpy(outdir,argv[i]); i++; } else if (!strcmp(argv[i],"-to")) { i++; if ((argc==i)||(argv[i][0]=='-')) { fprintf (stderr,"I Expect a file type as argument to '-to'\n"); Usage(argv[0]); } Opt_to.push_back(std::string(argv[i])); if (!ndfield::IO::canSave(Opt_to.back())) { fprintf (stderr,"Error: format '%s' is unknown or read-only.\n",argv[i]); Usage(argv[0]); } i++; } else { printf ("\nWhat is %s ???\n",argv[i]); Usage(argv[0]); } } verbose=2; bool needSave=false; if (!Opt_outName) strcpy(outname,CutName(fName)); else needSave=true; if (Opt_outDir) { needSave=true; strcpy(tmpname,outdir); if (outdir[strlen(outdir)-1]!='/') sprintf(outdir,"%s/",tmpname); sprintf(tmpname,"%s%s",outdir,outname); strcpy(outname,tmpname); } NDfield *field=ndfield::IO::load(std::string(fName)); if (Opt_info) { printf("field statistics:\n"); printNDfieldStat(field,3); } if (Opt_to.size()) { for (i=0;i<Opt_to.size();i++) ndfield::IO::save(field,std::string(outname)+ndfield::IO::getExtension(Opt_to[i]),Opt_to[i]); } else if (needSave) ndfield::IO::save(field,std::string(outname)+ndfield::IO::getExtension()); Free_NDfield(&field); return 0; }
void RetroArchTools::on_genPlaylistBtn_clicked() { d2pdatacurrent.systemname = ui->nosinput->text(); d2pdatacurrent.extension = ui->feinput->text(); d2pdatacurrent.corename = ui->noecinput->text(); d2pdatacurrent.corepath = ui->ptcinput->text(); d2pdatacurrent.rompath = ui->ptrinput->text(); if (!inputExists(d2pdatacurrent.systemname)) { QMessageBox::warning(this,tr("Error!"),tr("Please input the name of the system.")); return; } if (!inputExists(d2pdatacurrent.extension) || d2pdatacurrent.extension == ".") { QMessageBox::warning(this,tr("Error!"),tr("Please input the rom extension.")); return; } if (!inputExists(d2pdatacurrent.corename)) { d2pdatacurrent.corename = "DETECT"; } if (d2pdatacurrent.extension[0] != '.') { QMessageBox::warning(this,tr("Error!"),tr("File extension must begin with a '.'")); return; } if (!fileExists(d2pdatacurrent.corepath) || !isFile(d2pdatacurrent.corepath)) { if (inputExists(d2pdatacurrent.corepath)) { QMessageBox::warning(this,tr("Error!"),tr("Cannot find emulator core file!")); return; } else { d2pdatacurrent.corepath = "DETECT"; } } if (!fileExists(d2pdatacurrent.rompath) || isFile(d2pdatacurrent.rompath)) { QMessageBox::warning(this,tr("Error!"),tr("Cannot find rom directory!")); return; } if (!fileExists(d2pdatacurrent.playlistpath) || isFile(d2pdatacurrent.playlistpath)) { QMessageBox::warning(this,tr("Error!"),tr("Cannot find playlist directory!")); return; } QString playlistfile = QDir(d2pdatacurrent.playlistpath).filePath(d2pdatacurrent.systemname + ".lpl"); QFile playlist(playlistfile); QDir romdir(d2pdatacurrent.rompath); QStringList filters; filters << "*" + d2pdatacurrent.extension; QFileInfoList *roms = new QFileInfoList(romdir.entryInfoList(filters)); int crc = 1; if (playlist.open(QFile::WriteOnly | QFile::Truncate)) { QTextStream out(&playlist); for(const auto &fileName : *roms) { out << QDir::toNativeSeparators(fileName.absoluteFilePath()) + "\n"; out << fileName.baseName() + "\n"; out << QDir::toNativeSeparators(d2pdatacurrent.corepath) + "\n"; out << d2pdatacurrent.corename + "\n"; out << QString::number(crc) + "|crc\n"; out << d2pdatacurrent.systemname + ".lpl\n"; crc++; } playlist.close(); } else { QMessageBox::warning(this,tr("Error!"),tr("Error writing to playlist (check the file isn't being used somewhere)")); delete roms; return; } delete roms; QMessageBox::information(this,tr("Finished!"),"Playlist file created at " + playlistfile); }
int isCommand( struct directory* cluster, unsigned char* buffer, unsigned int FDS, unsigned int SPC, unsigned int RSC, unsigned int BPS, char* input, char* args ) { /* Make a copy of args; iterate through it with strtok; count arguments */ int argumentCount = 0; char * tempArgs = malloc( 1 + strlen ( args )); strcpy( tempArgs, args ); for( tempArgs = strtok( tempArgs, " " ); tempArgs; tempArgs = strtok( NULL, " " )) { argumentCount++; } // printf( "Number of args: %d\n", argumentCount ); int dir_result = isDir( cluster, args ); int file_result = isFile( cluster, args ); int r,w; /* OPEN */ if( strcmp( input, "open" ) == 0 ){ // check number of args: if( checkArgumentCount( argumentCount, OPEN_ARG_NUM )) return 1; char * mode = calloc( sizeof( char ), 2 ); char * ptr = calloc( sizeof( char ), 64 ); ptr = strtok( args, " " ); mode = strtok( NULL, " " ); open( args, mode ); return 1; } /* CLOSE */ else if(strcmp(input,"close") == 0){ // check number of args: if( checkArgumentCount( argumentCount, CLOSE_ARG_NUM )) return 1; close(args); return 1; } /* CREATE */ else if(strcmp(input,"create") == 0){ // check number of args: if( checkArgumentCount( argumentCount, CREATE_ARG_NUM )) return 1; if(fileExists(buffer,args,currentClusterNumber(GET,0),FDS,SPC,RSC,BPS) == 1){ printf("error: File already exists\n"); return 1; } r = checkIfClusterIsFull(buffer,currentClusterNumber(GET,0),FDS,SPC,RSC,BPS); if(r == 1){ //cluster is full, allocate new space //get space for new link in cluster chain r = findEmptyCluster(buffer,FDS,SPC,RSC,BPS); //extend the cluster chain using the new link extendClusterChain(buffer,r,currentClusterNumber(GET,0),FDS,SPC,RSC,BPS); //get space for the new file being created r = findEmptyCluster(buffer,FDS,SPC,RSC,BPS); //create new file r = create(buffer,args,r,currentClusterNumber(GET,0),FDS,SPC,RSC,BPS); if(r > 0){ FILE *fileptr; fileptr = fopen("fat32.img", "wb"); fwrite(buffer,1,67108864,fileptr); fclose(fileptr); }else if(r == 0){ printf("error: File already exists\n"); }else if(r < 0){ printf("error: out of useable space!\n"); } }else{ //cluster has room, put new file in that space r = findEmptyCluster(buffer,FDS,SPC,RSC,BPS); r = create(buffer,args,r,currentClusterNumber(GET,0),FDS,SPC,RSC,BPS); if(r > 0){ FILE *fileptr; fileptr = fopen("fat32.img", "wb"); fwrite(buffer,1,67108864,fileptr); fclose(fileptr); }else if(r == 0){ printf("error: File already exists\n"); }else if(r < 0){ printf("error: out of useable space!\n"); } } return 1; } /* RMDIR */ else if(strcmp(input,"rmdir") == 0){ // check number of args: if( checkArgumentCount( argumentCount, RMDIR_ARG_NUM )) return 1; r = rmdir(buffer,args,currentClusterNumber(GET,0),FDS,SPC,RSC,BPS); if(r == 1){ FILE *fileptr; fileptr = fopen("fat32.img", "wb"); fwrite(buffer,1,67108864,fileptr); fclose(fileptr); }else if(r == 0){ printf("error: does not exist\n"); }else if(r == -1){ printf("error: not a directory\n"); }else{ printf("error: directory not empty\n"); } return 1; } /* RM */ else if(strcmp(input,"rm") == 0){ // check number of args: if( checkArgumentCount( argumentCount, RM_ARG_NUM )) return 1; r = rm(buffer,args,currentClusterNumber(GET,0),FDS,SPC,RSC,BPS); if(r == 1){ close_without_check(args); FILE *fileptr; fileptr = fopen("fat32.img", "wb"); fwrite(buffer,1,67108864,fileptr); fclose(fileptr); }else if(r == 0){ printf("error: does not exist\n"); }else{ printf("error: not a file\n"); } return 1; } /* SIZE */ else if(strcmp(input,"size") == 0){ // check number of args: if( checkArgumentCount( argumentCount, SIZE_ARG_NUM )) return 1; size(buffer,args,currentClusterNumber(GET,0),FDS,SPC,RSC,BPS); return 1; } /* CD */ else if(strcmp(input,"cd") == 0){ // check number of args: if( checkArgumentCount( argumentCount, CD_ARG_NUM )) return 1; if(dir_result == -1){ //current dir //dont change currentClusterNumber }else if(dir_result == -2){ currentClusterNumber(SET, cd_back(buffer, currentClusterNumber(GET,0), FDS,SPC,RSC,BPS) ); return 3; }else{ r = cd(buffer,args,currentClusterNumber(GET,0),FDS,SPC,RSC,BPS); if(r > 0){ currentClusterNumber(SET,r); return 2; }else{ printf("%s: Invalid directory\n",args); } } return 1; } /* LS */ else if(strcmp(input,"ls") == 0){ // check number of args: if( checkArgumentCount( argumentCount, LS_ARG_NUM )) return 1; if(dir_result > 0){ ls(buffer,args,dir_result,FDS,SPC, RSC, BPS); } else if(dir_result < 0){ ls(buffer,args,currentClusterNumber(GET,0),FDS,SPC,RSC,BPS); } else printf("%s: Invalid directory\n",args); return 1; } /* MKDIR */ else if(strcmp(input,"mkdir") == 0){ int datacnum, dotcnum; // check number of args: if( checkArgumentCount( argumentCount, MKDIR_ARG_NUM )) return 1; if(fileExists(buffer,args,currentClusterNumber(GET,0),FDS,SPC,RSC,BPS) == 1){ printf("error: directory already exists\n"); return 1; } r = checkIfClusterIsFull(buffer,currentClusterNumber(GET,0),FDS,SPC,RSC,BPS); if(r == 1){ //cluster is full, allocate new space //get space for new link in cluster chain dotcnum = findEmptyCluster(buffer,FDS,SPC,RSC,BPS); //extend the cluster chain using the new link extendClusterChain(buffer,dotcnum,currentClusterNumber(GET,0),FDS,SPC,RSC,BPS); //get space for the new dir being created datacnum = findEmptyCluster(buffer,FDS,SPC,RSC,BPS); //create new directory r = mkdir(buffer,args,r,currentClusterNumber(GET,0),FDS,SPC,RSC,BPS); if(r > 0){ makeDotDirectories(buffer,(datacnum-2)*SPC+FDS,dotcnum,currentClusterNumber(GET,0)); FILE *fileptr; fileptr = fopen("fat32.img", "wb"); fwrite(buffer,1,67108864,fileptr); fclose(fileptr); }else if(r == 0){ printf("error: directory already exists\n"); }else if(r < 0){ printf("error: out of useable space!\n"); } }else{ //cluster has room, put new file in that space datacnum = findEmptyCluster(buffer,FDS,SPC,RSC,BPS); r = mkdir(buffer,args,datacnum,currentClusterNumber(GET,0),FDS,SPC,RSC,BPS); if(r > 0){ makeDotDirectories(buffer,(datacnum-2)*SPC+FDS,datacnum,currentClusterNumber(GET,0)); FILE *fileptr; fileptr = fopen("fat32.img", "wb"); fwrite(buffer,1,67108864,fileptr); fclose(fileptr); }else if(r == 0){ printf("error: directory already exists\n"); }else if(r < 0){ printf("error: out of useable space!\n"); } } return 1; } /* READ */ else if(strcmp(input,"read") == 0){ // check number of args: if( checkArgumentCount( argumentCount, READ_ARG_NUM )) return 1; char* file = calloc(sizeof(char),64); long int start, num_bytes; char *pEnd; char *temp1 = calloc(sizeof(char),8); char *temp2 = calloc(sizeof(char),8); file = strtok(args," "); r = fileModeIsReadable(file); if(r == 1){ temp1 = strtok(NULL," "); start = strtol(temp1,&pEnd,10); temp2 = strtok(NULL," "); num_bytes = strtol(temp2,&pEnd,10); if(start >= SIZE_OF_SECTOR){ printf( "Error: attempt to read beyond EoF\n" ); }else{ read( buffer, file, start, num_bytes, currentClusterNumber( GET, 0 ), FDS, SPC, RSC, BPS ); } }else{ printf( "Error: file is not open for writing!\n" ); } return 1; } /* WRITE */ else if( strcmp( input, "write" ) == 0 ){ // check number of args: if( checkArgumentCount( argumentCount, WRITE_ARG_NUM )) return 1; char* file = calloc(sizeof(char),64); long int start, num_bytes; char *pEnd; char *temp1 = calloc(sizeof(char),8); char *temp2 = calloc(sizeof(char),8); char *temp3 = calloc(sizeof(char),8); file = strtok(args," "); w = fileModeIsWriteable(file); if(w == 1){ temp1 = strtok(NULL," "); start = strtol(temp1,&pEnd,10); temp2 = strtok(NULL," "); num_bytes = strtol(temp2,&pEnd,10); temp3 = strtok(NULL,"\n"); if(strlen(temp3) != num_bytes){ printf("Error: Bytes requested does not match string size!\n"); return 1; } if(start >= SIZE_OF_SECTOR){ printf("Error: attempt to read beyond EoF\n"); }else{ FILE *fileptr; long filelen; write(buffer,file,start,num_bytes,temp3,currentClusterNumber(GET,0),FDS,SPC,RSC,BPS); //find the file length fileptr = fopen("fat32.img", "rb"); fseek(fileptr, 0, SEEK_END); filelen = ftell(fileptr); fclose(fileptr); //write to file fileptr = fopen("fat32.img", "wb"); fwrite(buffer,1,filelen,fileptr); fclose(fileptr); } }else{ printf("Error: file is not open for writing!\n"); } return 1; } /* EXIT */ else if( strcmp( input,"exit" ) == 0 ){ printf( "Goodbye!\n" ); exit( 1 ); }else return 0; }
bool Project::Item::isImageFile() const { return isFile() && (ImageFileFormat::findImageFormatForFileExtension (getFile()) != nullptr || getFile().hasFileExtension ("svg")); }
bool Project::Item::isImageFile() const { return isFile() && getFile().hasFileExtension ("png;jpg;jpeg;gif;drawable"); }
void Project::Item::setFile (const RelativePath& file) { jassert (isFile()); state.setProperty (Ids::file, file.toUnixStyle(), getUndoManager()); state.setProperty (Ids::name, file.getFileName(), getUndoManager()); }
Foam::fileNameList Foam::findEtcFiles(const fileName& name, bool mandatory) { fileNameList results; // Search for user files in // * ~/.OpenFOAM/VERSION // * ~/.OpenFOAM // fileName searchDir = home()/".OpenFOAM"; if (isDir(searchDir)) { fileName fullName = searchDir/FOAMversion/name; if (isFile(fullName)) { results.append(fullName); } fullName = searchDir/name; if (isFile(fullName)) { results.append(fullName); } } // Search for group (site) files in // * $WM_PROJECT_SITE/VERSION // * $WM_PROJECT_SITE // searchDir = getEnv("WM_PROJECT_SITE"); if (searchDir.size()) { if (isDir(searchDir)) { fileName fullName = searchDir/FOAMversion/name; if (isFile(fullName)) { results.append(fullName); } fullName = searchDir/name; if (isFile(fullName)) { results.append(fullName); } } } else { // OR search for group (site) files in // * $WM_PROJECT_INST_DIR/site/VERSION // * $WM_PROJECT_INST_DIR/site // searchDir = getEnv("WM_PROJECT_INST_DIR"); if (isDir(searchDir)) { fileName fullName = searchDir/"site"/FOAMversion/name; if (isFile(fullName)) { results.append(fullName); } fullName = searchDir/"site"/name; if (isFile(fullName)) { results.append(fullName); } } } // Search for other (shipped) files in // * $WM_PROJECT_DIR/etc // searchDir = getEnv("WM_PROJECT_DIR"); if (isDir(searchDir)) { fileName fullName = searchDir/"etc"/name; if (isFile(fullName)) { results.append(fullName); } } // Not found if (results.empty()) { // Abort if the file is mandatory, otherwise return null if (mandatory) { std::cerr << "--> FOAM FATAL ERROR in Foam::findEtcFiles() :" " could not find mandatory file\n '" << name.c_str() << "'\n\n" << std::endl; ::exit(1); } } // Return list of matching paths or empty list if none found return results; }
//-***************************************************************************** int main( int argc, char *argv[] ) { bool opt_all = false; bool opt_meta = false; std::string desc( "abctree [OPTION] FILE[/NAME]\n" " -a include properties listings\n" " -h, --help prints this help message\n" " -m print metadata\n" ); // check for min args if ( argc < 2 ) { std::cout << desc << std::endl; return 0; }; // parse args std::vector<std::string> arguments(argv, argv + argc); std::vector<std::string> options; std::vector<std::string> files; // separate file args from option args for ( std::size_t i = 1; i < arguments.size(); i++ ) { if ( arguments[ i ].substr( 0, 1 ) == "-" ) options.push_back( arguments[ i ] ); else files.push_back( arguments[ i ] ); } // help if ( argc < 2 || optionExists( options, "h" ) || optionExists( options, "help" ) ) { std::cout << desc << std::endl; return 0; }; // set some flags opt_all = optionExists( options, "a"); opt_meta = optionExists( options, "m"); // open each file size_t count = 0; for ( std::size_t i = 0; i < files.size(); i++ ) { if ( files.size() > 1 ) std::cout << BOLD << files[i] << ':' << RESETCOLOR << std::endl; std::stringstream ss( files[i] ); std::stringstream fp; std::string segment; std::vector<std::string> seglist; /* * separate file and object paths, e.g. * * ../dir1/foo.abc/bar/baz * \_____________/\______/ * file obj */ int j = 0; while ( std::getline( ss, segment, '/' ) ) { if ( !isFile ( fp.str() ) ) { if ( j != 0 ) fp << "/"; fp << segment; } else { seglist.push_back( segment ); } ++j; } // open the iarchive Abc::IArchive archive; AbcF::IFactory factory; factory.setPolicy(Abc::ErrorHandler::kQuietNoopPolicy); AbcF::IFactory::CoreType coreType; archive = factory.getArchive(std::string( fp.str() ), coreType); // display file metadata if ( opt_meta ) { std::cout << "Using " << Alembic::AbcCoreAbstract::GetLibraryVersion () << std::endl;; std::string appName; std::string libraryVersionString; Alembic::Util::uint32_t libraryVersion; std::string whenWritten; std::string userDescription; std::string coreName; GetArchiveInfo (archive, appName, libraryVersionString, libraryVersion, whenWritten, userDescription); if ( coreType == AbcF::IFactory::kOgawa ) { coreName = "Ogawa"; } else if ( coreType == AbcF::IFactory::kHDF5 ) { coreName = "HDF5"; } else { coreName = "Unknown"; }; if ( appName != "" ) { std::cout << " file written by: " << appName << std::endl; std::cout << " using Alembic : " << libraryVersionString << std::endl; std::cout << " written on : " << whenWritten << std::endl; std::cout << " user description : " << userDescription << std::endl; } else { std::cout << " (file doesn't have any ArchiveInfo)" << std::endl; } std::cout << " core type : " << coreName << std::endl; }; // walk object hierarchy and find valid objects AbcG::IObject test = archive.getTop(); AbcG::IObject iObj = test; while ( test.valid() && seglist.size() > 0 ) { test = test.getChild( seglist.front() ); if ( test.valid() ) { iObj = test; seglist.erase( seglist.begin() ); } } // walk property hierarchy for most recent valid object Abc::ICompoundProperty props = iObj.getProperties(); const Abc::PropertyHeader* header; bool found = false; for ( std::size_t i = 0; i < seglist.size(); ++i ) { header = props.getPropertyHeader( seglist[i] ); if ( header && header->isCompound() ) { Abc::ICompoundProperty ptest( props, header->getName() ); if ( ptest.valid() ) { props = ptest; found = true; } } else if ( header && header->isSimple() ) { found = true; } else { std::cout << seglist[i] << ": Invalid object or property" << std::endl; return 1; } } // walk the archive tree if ( found ) if ( header->isCompound() ) tree( props ); else tree( Abc::IScalarProperty( props, header->getName() ) ); else tree( iObj, opt_all ); ++count; } return 0; }